[maven-release-plugin] copy for tag wamblee-utils-0.2.1
authorerik <erik@77661180-640e-0410-b3a8-9f9b13e6d0e0>
Tue, 13 Apr 2010 19:25:12 +0000 (19:25 +0000)
committererik <erik@77661180-640e-0410-b3a8-9f9b13e6d0e0>
Tue, 13 Apr 2010 19:25:12 +0000 (19:25 +0000)
377 files changed:
tags/wamblee-utils-0.2.1/ABOUT.txt [new file with mode: 0644]
tags/wamblee-utils-0.2.1/LICENSE [new file with mode: 0644]
tags/wamblee-utils-0.2.1/README.txt [new file with mode: 0644]
tags/wamblee-utils-0.2.1/TODO.txt [new file with mode: 0644]
tags/wamblee-utils-0.2.1/build/checkstyle-noframes.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/build/checkstyle-simple.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/build/style.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/hibernate-jpa/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/release.sh [new file with mode: 0755]
tags/wamblee-utils-0.2.1/security/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AllOperation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/Operation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/PathCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/UserCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/Group.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/GroupSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/NameValidator.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/User.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAccessor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdministration.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserMgtException.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/AuthorizationRule.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/AuthorizationService.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/Group.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/OperationCondition.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/OperationCondition.hbm.xmlxx [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PageAuthorizationRule.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PathCondition.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PhotoAuthorizationRule.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/TestAuthorizationRule.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/User.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/UserCondition.hbm.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/ehcache.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/hibernate.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/properties/org.wamblee.security.ehcache.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.authorization.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.usermgt-repositories.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.usermgt.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/resources/properties/test.org.wamblee.security.database.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/resources/properties/test.org.wamblee.security.usermgt.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.datasource.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.properties.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.useraccessor.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.usermgtinitializer.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/Cache.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/CachedObject.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/EhCache.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/ForeverCache.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/ZeroCache.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/Lock.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/AndCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/Condition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/OrCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanKernel.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/Pair.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/ClassPathResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/FileResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/InputResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/SimpleProcess.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/StreamResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/Observable.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/Observer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/Persistent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/DomUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/XMLException.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/XslTransformer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/main/resources/log4j.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/TestBean.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/PairTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/FileResourceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/TestData.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/TestResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/observer/ObservableTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/AssertionUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/EventTracker.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/TimingUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/XmlUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/cache/ehcache.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beanRefContext.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beankernel-wrong.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beankernel.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/spring1.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/io/myresource.txt [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/output-reportToHtml-report.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/report.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml-invalid.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml-nonwellformed.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml2.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToText.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/utilities.xsl [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/package.html [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/TODO.txt [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/components/ORMappingConfig.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/container/Container.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/Component.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/Scope.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Edge.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Graph.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Node.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Visitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/package-info.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X1.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X10.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X11.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X2.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X3.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X4.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X5.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X6.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X7.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X8.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X9.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/container/Application.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/Environment.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/StringComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/MyNode.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/resources/properties/org.wamblee.system.spring.component.hibernate.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/main/resources/spring/org.wamblee.system.spring.component.hibernate.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.spring.properties [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.spring.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties2.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithRequirements.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContext.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContextFactory.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabase.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabaseProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaTables.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/Database.java [new file with mode: 0755]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseBuilder.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseDescription.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseStarter.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseUtils.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabase.java [new file with mode: 0755]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabase.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabaseProvider.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaBuilder.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizerBuilder.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaTester.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/PersistenceUnitDescription.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/package-info.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/main/resources/META-INF/services/org.wamblee.support.persistence.DatabaseProvider [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/jndi/StubInitiaContextFactoryTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseBuilderTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseUtilsTestBase.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DerbyDatabaseTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/ExternalDatabaseTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntity.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntityExampleTestBase.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyPersistenceUnit.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyTables.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/enterprise/src/test/resources/META-INF/persistence.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/hibernate/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/hibernate/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/pom.xml [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java [new file with mode: 0644]
tags/wamblee-utils-0.2.1/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java [new file with mode: 0644]

diff --git a/tags/wamblee-utils-0.2.1/ABOUT.txt b/tags/wamblee-utils-0.2.1/ABOUT.txt
new file mode 100644 (file)
index 0000000..8d0afc9
--- /dev/null
@@ -0,0 +1,4 @@
+This is the utilities project of wamblee.org. It contains various utilities
+and useful programs for various purposes. The most important part is the 
+support library. 
+
diff --git a/tags/wamblee-utils-0.2.1/LICENSE b/tags/wamblee-utils-0.2.1/LICENSE
new file mode 100644 (file)
index 0000000..d645695
--- /dev/null
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/tags/wamblee-utils-0.2.1/README.txt b/tags/wamblee-utils-0.2.1/README.txt
new file mode 100644 (file)
index 0000000..a41ba43
--- /dev/null
@@ -0,0 +1,37 @@
+Support utilities for enterprise development
+============================================
+
+* support: Base (non-Java EE) support
+* system:  An IOC framework experiment. This should be flexible enough as a basis for 
+  a CDI implementation. It currently offers only a programmatic API and does not use
+  annotations.  
+* hibernate-jpa: Hibernate JPA dependencies
+* security: Security support utlities (user management and authorization)
+* test: Test support for JEE testing. In particular, junit testing with an inmemory or
+  external database and support for JPA testing with several JPA providers. 
+  
+
+To be removed from this project (currently skipped from the release)
+====================================================================
+
+* socketproxy: An old socketproxy. To be removed from the utilities
+* mythtv: An application for exposing mythtv recordings in a useful directory structure
+  This will be removed from the utilities
+
+To be added to this project
+===========================
+* utilities for CDI
+* wicket utilities. 
+
+Building
+========
+
+You need maven2 and java 6 
+
+Releasing
+=========
+
+Trigger release settings by building with -Dwamblee.release=true
+This will skip some projects that are not to be released. 
+
+
diff --git a/tags/wamblee-utils-0.2.1/TODO.txt b/tags/wamblee-utils-0.2.1/TODO.txt
new file mode 100644 (file)
index 0000000..6efaa91
--- /dev/null
@@ -0,0 +1,12 @@
+* refactor: Create jpa subproject with separate subprojects for api, hibernate, 
+  toplink-essentials and eclipselink
+  Each subproject contains the required repo settings
+* Maven profile for nonrelease which is dactivated when release is active.
+* Have toplink, eclipselink, hibernate profiles that are deactivated by 
+  release and active by default. 
+  
+* add cdi subproject to the utils
+* add schemagen for user management part. 
+* JPA 2.0 implementation for security. 
+
diff --git a/tags/wamblee-utils-0.2.1/build/checkstyle-noframes.xsl b/tags/wamblee-utils-0.2.1/build/checkstyle-noframes.xsl
new file mode 100644 (file)
index 0000000..5f18134
--- /dev/null
@@ -0,0 +1,179 @@
+<xsl:stylesheet        xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">\r
+<xsl:output method="html" indent="yes"/>\r
+<xsl:decimal-format decimal-separator="." grouping-separator="," />\r
+\r
+<!-- Checkstyle XML Style Sheet by Stephane Bailliez <sbailliez@apache.org>         -->\r
+<!-- Part of the Checkstyle distribution found at http://checkstyle.sourceforge.net -->\r
+<!-- Usage (generates checkstyle_report.html):                                      -->\r
+<!--    <checkstyle failonviolation="false" config="${check.config}">               -->\r
+<!--      <fileset dir="${src.dir}" includes="**/*.java"/>                          -->\r
+<!--      <formatter type="xml" toFile="${doc.dir}/checkstyle_report.xml"/>         -->\r
+<!--    </checkstyle>                                                               -->\r
+<!--    <style basedir="${doc.dir}" destdir="${doc.dir}"                            -->\r
+<!--            includes="checkstyle_report.xml"                                    -->\r
+<!--            style="${doc.dir}/checkstyle-noframes.xsl"/>                        -->\r
+\r
+<xsl:template match="checkstyle">\r
+       <html>\r
+               <head>\r
+               <style type="text/css">\r
+    .bannercell {\r
+      border: 0px;\r
+      padding: 0px;\r
+    }\r
+    body {\r
+      margin-left: 10;\r
+      margin-right: 10;\r
+      font:normal 80% arial,helvetica,sanserif;\r
+      background-color:#FFFFFF;\r
+      color:#000000;\r
+    }\r
+    .a td { \r
+      background: #efefef;\r
+    }\r
+    .b td { \r
+      background: #fff;\r
+    }\r
+    th, td {\r
+      text-align: left;\r
+      vertical-align: top;\r
+    }\r
+    th {\r
+      font-weight:bold;\r
+      background: #ccc;\r
+      color: black;\r
+    }\r
+    table, th, td {\r
+      font-size:100%;\r
+      border: none\r
+    }\r
+    table.log tr td, tr th {\r
+      \r
+    }\r
+    h2 {\r
+      font-weight:bold;\r
+      font-size:140%;\r
+      margin-bottom: 5;\r
+    }\r
+    h3 {\r
+      font-size:100%;\r
+      font-weight:bold;\r
+      background: #525D76;\r
+      color: white;\r
+      text-decoration: none;\r
+      padding: 5px;\r
+      margin-right: 2px;\r
+      margin-left: 2px;\r
+      margin-bottom: 0;\r
+    }\r
+               </style>\r
+               </head>\r
+               <body>\r
+                       <a name="top"></a>\r
+      <!-- jakarta logo -->\r
+      <table border="0" cellpadding="0" cellspacing="0" width="100%">\r
+      <tr>\r
+        <td class="bannercell" rowspan="2">\r
+          <!--a href="http://jakarta.apache.org/">\r
+          <img src="http://jakarta.apache.org/images/jakarta-logo.gif" alt="http://jakarta.apache.org" align="left" border="0"/>\r
+          </a-->\r
+        </td>\r
+               <td class="text-align:right"><h2>CheckStyle Audit</h2></td>\r
+               </tr>\r
+               <tr>\r
+               <td class="text-align:right">Designed for use with <a href='http://checkstyle.sourceforge.net/'>CheckStyle</a> and <a href='http://jakarta.apache.org'>Ant</a>.</td>\r
+               </tr>\r
+      </table>\r
+       <hr size="1"/>\r
+                       \r
+                       <!-- Summary part -->\r
+                       <xsl:apply-templates select="." mode="summary"/>\r
+                       <hr size="1" width="100%" align="left"/>\r
+                       \r
+                       <!-- Package List part -->\r
+                       <xsl:apply-templates select="." mode="filelist"/>\r
+                       <hr size="1" width="100%" align="left"/>\r
+                       \r
+                       <!-- For each package create its part -->\r
+                       <xsl:for-each select="file">\r
+                         <xsl:sort select="@name"/>\r
+                         <xsl:apply-templates select="."/>\r
+                         <p/>\r
+                         <p/>\r
+                       </xsl:for-each>\r
+                       <hr size="1" width="100%" align="left"/>\r
+                       \r
+                       \r
+               </body>\r
+       </html>\r
+</xsl:template>\r
+       \r
+       \r
+       \r
+       <xsl:template match="checkstyle" mode="filelist">       \r
+               <h3>Files</h3>\r
+               <table class="log" border="0" cellpadding="5" cellspacing="2" width="100%">\r
+      <tr>\r
+        <th>Name</th>\r
+        <th>Errors</th>\r
+      </tr>\r
+                       <xsl:for-each select="file">\r
+                               <xsl:sort select="@name"/>\r
+                               <xsl:variable name="errorCount" select="count(error)"/>                         \r
+                               <tr>\r
+          <xsl:call-template name="alternated-row"/>\r
+                                       <td><a href="#f-{@name}"><xsl:value-of select="@name"/></a></td>\r
+                                       <td><xsl:value-of select="$errorCount"/></td>\r
+                               </tr>\r
+                       </xsl:for-each>\r
+               </table>                \r
+       </xsl:template>\r
+       \r
+       \r
+       <xsl:template match="file">\r
+    <a name="f-{@name}"></a>\r
+    <h3>File <xsl:value-of select="@name"/></h3>\r
+    \r
+    <table class="log" border="0" cellpadding="5" cellspacing="2" width="100%">\r
+       <tr>\r
+         <th>Error Description</th>\r
+         <th>Line</th>\r
+      </tr>\r
+      <xsl:for-each select="error">\r
+       <tr>\r
+        <xsl:call-template name="alternated-row"/>\r
+         <td><xsl:value-of select="@message"/></td>\r
+         <td><xsl:value-of select="@line"/></td>\r
+       </tr>\r
+       </xsl:for-each>\r
+    </table>\r
+    <a href="#top">Back to top</a>\r
+       </xsl:template>\r
+       \r
+       \r
+       <xsl:template match="checkstyle" mode="summary">\r
+               <h3>Summary</h3>\r
+               <xsl:variable name="fileCount" select="count(file)"/>\r
+               <xsl:variable name="errorCount" select="count(file/error)"/>\r
+               <table class="log" border="0" cellpadding="5" cellspacing="2" width="100%">\r
+               <tr>\r
+                       <th>Files</th>\r
+                       <th>Errors</th>\r
+               </tr>\r
+               <tr>\r
+                 <xsl:call-template name="alternated-row"/>\r
+                       <td><xsl:value-of select="$fileCount"/></td>\r
+                       <td><xsl:value-of select="$errorCount"/></td>\r
+               </tr>\r
+               </table>\r
+       </xsl:template>\r
+       \r
+  <xsl:template name="alternated-row">\r
+    <xsl:attribute name="class">\r
+      <xsl:if test="position() mod 2 = 1">a</xsl:if>\r
+      <xsl:if test="position() mod 2 = 0">b</xsl:if>\r
+    </xsl:attribute>  \r
+  </xsl:template>      \r
+</xsl:stylesheet>\r
+\r
+\r
diff --git a/tags/wamblee-utils-0.2.1/build/checkstyle-simple.xsl b/tags/wamblee-utils-0.2.1/build/checkstyle-simple.xsl
new file mode 100644 (file)
index 0000000..d98cbcb
--- /dev/null
@@ -0,0 +1,71 @@
+<?xml version="1.0"?>\r
+\r
+<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\r
+\r
+<xsl:template match="/">\r
+  <html>\r
+    <head>\r
+    <title>Sun Coding Style Violations</title>\r
+    </head>\r
+    <body bgcolor="#FFFFEF">\r
+    <p><b>Coding Style Check Results</b></p>\r
+    <table border="1" cellspacing="0" cellpadding="2">\r
+       <tr bgcolor="#CC9966">\r
+           <th colspan="2"><b>Summary</b></th>\r
+       </tr>\r
+       <tr bgcolor="#CCF3D0">\r
+           <td>Total files checked</td>\r
+           <td><xsl:number level="any" value="count(descendant::file)"/></td>\r
+       </tr>\r
+       <tr bgcolor="#F3F3E1">\r
+           <td>Files with errors</td>\r
+           <td><xsl:number level="any" value="count(descendant::file[error])"/></td>\r
+       </tr>\r
+       <tr bgcolor="#CCF3D0">\r
+           <td>Total errors</td>\r
+           <td><xsl:number level="any" value="count(descendant::error)"/></td>\r
+       </tr>\r
+       <tr bgcolor="#F3F3E1">\r
+           <td>Errors per file</td>\r
+           <td><xsl:number level="any" value="count(descendant::error) div count(descendant::file)"/></td>\r
+       </tr>\r
+    </table>\r
+    <hr align="left" width="95%" size="1"/>\r
+    <p>The following are violations of the Sun Coding-Style Standards:</p>\r
+    <p/>\r
+       <xsl:apply-templates/>\r
+    </body>\r
+  </html>\r
+</xsl:template>\r
+\r
+<xsl:template match="file[error]">\r
+    <table bgcolor="#AFFFFF" width="95%" border="1" cellspacing="0" cellpadding="2">\r
+       <tr>\r
+           <th> File: </th>\r
+           <td>\r
+               <xsl:value-of select="@name"/>\r
+           </td>\r
+       </tr>\r
+    </table>\r
+    <table bgcolor="#DFFFFF" width="95%" border="1" cellspacing="0" cellpadding="2">\r
+       <tr>\r
+           <th> Line Number </th>\r
+           <th> Error Message </th>\r
+       </tr>\r
+       <xsl:apply-templates select="error"/>\r
+    </table>\r
+    <p/>\r
+</xsl:template>\r
+\r
+<xsl:template match="error">\r
+    <tr>\r
+       <td>\r
+           <xsl:value-of select="@line"/>\r
+       </td>\r
+       <td>\r
+           <xsl:value-of select="@message"/>\r
+       </td>\r
+    </tr>\r
+</xsl:template>\r
+\r
+</xsl:stylesheet>\r
diff --git a/tags/wamblee-utils-0.2.1/build/style.xml b/tags/wamblee-utils-0.2.1/build/style.xml
new file mode 100644 (file)
index 0000000..58b854e
--- /dev/null
@@ -0,0 +1,185 @@
+<?xml version="1.0"?>\r
+<!DOCTYPE module PUBLIC\r
+    "-//Puppy Crawl//DTD Check Configuration 1.2//EN"\r
+    "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">\r
+\r
+<!--\r
+\r
+  Checkstyle configuration that checks the sun coding conventions from:\r
+\r
+    - the Java Language Specification at\r
+      http://java.sun.com/docs/books/jls/second_edition/html/index.html\r
+\r
+    - the Sun Code Conventions at http://java.sun.com/docs/codeconv/\r
+\r
+    - the Javadoc guidelines at\r
+      http://java.sun.com/j2se/javadoc/writingdoccomments/index.html\r
+\r
+    - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html\r
+\r
+    - some best practices\r
+\r
+  Checkstyle is very configurable. Be sure to read the documentation at\r
+  http://checkstyle.sf.net (or in your downloaded distribution).\r
+\r
+  Most Checks are configurable, be sure to consult the documentation.\r
+\r
+  To completely disable a check, just comment it out or delete it from the file.\r
+\r
+  Finally, it is worth reading the documentation.\r
+\r
+-->\r
+\r
+<module name="Checker">\r
+\r
+    <!-- Checks that a package.html file exists for each package.     -->\r
+    <!-- See http://checkstyle.sf.net/config_javadoc.html#PackageHtml -->\r
+    <!-- module name="PackageHtml"/ -->\r
+\r
+    <!-- Checks whether files end with a new line.                        -->\r
+    <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->\r
+    <module name="NewlineAtEndOfFile"/>\r
+\r
+    <!-- Checks that property files contain the same keys.         -->\r
+    <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->\r
+    <module name="Translation"/>\r
+\r
+\r
+    <module name="TreeWalker">\r
+\r
+        <!-- Checks for Javadoc comments.                     -->\r
+        <!-- See http://checkstyle.sf.net/config_javadoc.html -->\r
+        <!-- module name="JavadocMethod"/ -->\r
+        <!-- module name="JavadocType"/ -->\r
+        <!-- module name="JavadocVariable"/ -->\r
+       <!-- module name="JavadocStyle"/ -->\r
+        \r
+        <!-- Checks for Naming Conventions.                  -->\r
+        <!-- See http://checkstyle.sf.net/config_naming.html -->\r
+        <module name="ConstantName"/>\r
+        <module name="LocalFinalVariableName"/>\r
+        <module name="LocalVariableName"/>\r
+        <module name="MemberName">
+            <property name="format" value="_[a-z][a-zA-Z0-9]*$"/>
+        </module>\r
+        <module name="MethodName" />\r
+        <module name="PackageName"/>\r
+        <module name="ParameterName">
+            <property name="format" value="^a[A-Z][a-zA-Z0-9]*$"/>
+        </module>\r
+        <module name="StaticVariableName">
+            <property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"/>
+        </module>\r
+        <module name="TypeName"/>\r
+\r
+\r
+        <!-- Checks for Headers                                -->\r
+        <!-- See http://checkstyle.sf.net/config_header.html   -->\r
+        <!-- <module name="Header">                            -->\r
+            <!-- The follow property value demonstrates the ability     -->\r
+            <!-- to have access to ANT properties. In this case it uses -->\r
+            <!-- the ${basedir} property to allow Checkstyle to be run  -->\r
+            <!-- from any directory within a project. See property      -->\r
+            <!-- expansion,                                             -->\r
+            <!-- http://checkstyle.sf.net/config.html#properties        -->\r
+            <!-- <property                                              -->\r
+            <!--     name="headerFile"                                  -->\r
+            <!--     value="${basedir}/java.header"/>                   -->\r
+        <!-- </module> -->\r
+\r
+        <!-- Following interprets the header file as regular expressions. -->\r
+        <!-- <module name="RegexpHeader"/>                                -->\r
+\r
+\r
+        <!-- Checks for imports                              -->\r
+        <!-- See http://checkstyle.sf.net/config_import.html -->\r
+        <module name="AvoidStarImport"/>\r
+        <module name="IllegalImport"/> <!-- defaults to sun.* packages -->\r
+        <module name="RedundantImport"/>\r
+        <module name="UnusedImports"/>\r
+\r
+\r
+        <!-- Checks for Size Violations.                    -->\r
+        <!-- See http://checkstyle.sf.net/config_sizes.html -->\r
+        <module name="FileLength"/>\r
+        <module name="LineLength">
+            <property name="max" value="120"/>
+        </module>\r
+        <module name="MethodLength"/>\r
+        <module name="ParameterNumber"/>\r
+\r
+\r
+        <!-- Checks for whitespace                               -->\r
+        <!-- See http://checkstyle.sf.net/config_whitespace.html -->\r
+        <module name="EmptyForIteratorPad"/>\r
+        <!-- module name="MethodParamPad"/ -->\r
+        <!-- module name="NoWhitespaceAfter"/ -->\r
+        <module name="NoWhitespaceBefore"/>\r
+        <module name="OperatorWrap"/>\r
+        <module name="ParenPad"/>\r
+        <!-- module name="TypecastParenPad"/ -->\r
+        <module name="TabCharacter"/>\r
+        <module name="WhitespaceAfter"/>\r
+        <!-- module name="WhitespaceAround">
+            <property name="tokens" value=" ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, LAND, LCURLY, LE, LITERAL_ASSERT, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR,MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY,SL,SLIST,SL_ASSIGN,SR,SR_ASSIGN,STAR,STAR_ASSIGN,GENERIC_START,GENERIC_END,TYPE_EXTENSION_AND,WILDCARD_TYPE"/>
+        </module -->\r
+\r
+\r
+        <!-- Modifier Checks                                    -->\r
+        <!-- See http://checkstyle.sf.net/config_modifiers.html -->\r
+        <module name="ModifierOrder"/>\r
+        <module name="RedundantModifier"/>\r
+\r
+\r
+        <!-- Checks for blocks. You know, those {}'s         -->\r
+        <!-- See http://checkstyle.sf.net/config_blocks.html -->\r
+        <module name="AvoidNestedBlocks">
+            <property name="allowInSwitchCase" value="true"/>
+        </module>\r
+        <module name="EmptyBlock"/>\r
+        <module name="LeftCurly"/>\r
+        <module name="NeedBraces"/>\r
+        <module name="RightCurly"/>\r
+\r
+\r
+        <!-- Checks for common coding problems               -->\r
+        <!-- See http://checkstyle.sf.net/config_coding.html -->\r
+        <module name="AvoidInlineConditionals"/>\r
+        <!-- module name="DoubleCheckedLocking"/ -->   \r
+        <module name="EmptyStatement"/>\r
+        <module name="EqualsHashCode"/>\r
+        <module name="HiddenField"/>\r
+        <module name="IllegalInstantiation"/>\r
+        <module name="InnerAssignment"/>\r
+        <module name="MagicNumber">
+            <property name="ignoreNumbers" value="-1,0,1,2,3,4"/>
+        </module>\r
+        <module name="MissingSwitchDefault"/>\r
+        <module name="RedundantThrows"/>\r
+        <module name="SimplifyBooleanExpression"/>\r
+        <module name="SimplifyBooleanReturn"/>\r
+        <!-- module name="ExplicitInitialization"/ -->\r
+\r
+        <!-- Checks for class design                         -->\r
+        <!-- See http://checkstyle.sf.net/config_design.html -->\r
+        <!-- module name="DesignForExtension"/ -->\r
+        <module name="FinalClass"/>\r
+        <module name="HideUtilityClassConstructor"/>\r
+        <module name="InterfaceIsType"/>\r
+        <module name="VisibilityModifier"/>\r
+\r
+\r
+        <!-- Miscellaneous other checks.                   -->\r
+        <!-- See http://checkstyle.sf.net/config_misc.html -->\r
+        <module name="ArrayTypeStyle"/>\r
+        <!-- module name="FinalParameters"/ -->\r
+        <!-- module name="GenericIllegalRegexp">\r
+            <property name="format" value="\s+$"/>\r
+            <property name="message" value="Line has trailing spaces."/>\r
+        </module -->\r
+        <module name="TodoComment"/>\r
+        <module name="UpperEll"/>\r
+\r
+    </module>\r
+\r
+</module>\r
diff --git a/tags/wamblee-utils-0.2.1/hibernate-jpa/pom.xml b/tags/wamblee-utils-0.2.1/hibernate-jpa/pom.xml
new file mode 100644 (file)
index 0000000..e1bcbdc
--- /dev/null
@@ -0,0 +1,46 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-hibernate-jpa</artifactId>
+  <packaging>jar</packaging>
+  <name>/hibernate-jpa</name>
+  <url>http://wamblee.org</url>
+  <dependencies>
+    <!-- This dependency should probably move to a more generic JPA 
+         project --> 
+    <dependency>
+      <groupId>javax.transaction</groupId>
+      <artifactId>transaction-api</artifactId>
+      <version>1.1</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.hibernate</groupId>
+      <artifactId>hibernate-entitymanager</artifactId>
+      <version>3.4.0.GA</version>
+      <exclusions>
+        <exclusion>
+          <groupId>javax.transaction</groupId>
+          <artifactId>jta</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+   
+  </dependencies>
+  
+  <!-- repositories>
+    <repository>
+      <id>jboss</id>
+      <name>JBoss Repo</name>
+      <url>http://repository.jboss.org/maven2</url>
+    </repository>
+  </repositories-->
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/pom.xml b/tags/wamblee-utils-0.2.1/pom.xml
new file mode 100644 (file)
index 0000000..9e1d53b
--- /dev/null
@@ -0,0 +1,572 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <packaging>pom</packaging>
+    <version>0.2.1</version>
+    <name>/</name>
+    <description>wamblee.org utilities library</description>
+    <url>http://wamblee.org</url>
+    <licenses>
+        <license>
+            <name>The Apache Software License, Version 2.0</name>
+            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
+            <distribution>repo</distribution>
+        </license>
+    </licenses>
+    <scm>
+        <url>https://wamblee.org/viewvc/utils/tags/wamblee-utils-0.2.1</url>
+        <connection>scm:svn:https://wamblee.org/svn/public/utils/tags/wamblee-utils-0.2.1</connection>
+    </scm>
+    <developers>
+        <developer>
+            <email>erik@wamblee.org</email>
+            <name>Erik Brakkee</name>
+            <url>http://brakkee.org</url>
+        </developer>
+    </developers>
+
+    <modules>
+        <module>support</module>
+        <module>system</module>
+        <module>hibernate-jpa</module>
+        <module>security</module>
+        <module>test</module>
+    </modules>
+    <dependencies>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.dbunit</groupId>
+            <artifactId>dbunit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.derby</groupId>
+            <artifactId>derby</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.derby</groupId>
+            <artifactId>derbyclient</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.derby</groupId>
+            <artifactId>derbynet</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-jdk14</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-all</artifactId>
+            <version>1.8.0</version>
+            <scope>test</scope>
+        </dependency>
+
+        <!-- dependency>
+          <groupId>org.testng</groupId>
+          <artifactId>testng</artifactId>
+          <version>5.7</version>
+          <scope>test</scope>
+          <classifier>jdk15</classifier>
+        </dependency -->
+    </dependencies>
+
+    <dependencyManagement>
+        <dependencies>
+
+            <dependency>
+                <groupId>oro</groupId>
+                <artifactId>oro</artifactId>
+                <version>2.0.6</version>
+            </dependency>
+
+
+            <dependency>
+                <groupId>javax.transaction</groupId>
+                <artifactId>transaction-api</artifactId>
+                <version>1.1</version>
+            </dependency>
+
+            <dependency>
+                <groupId>junit</groupId>
+                <artifactId>junit</artifactId>
+                <version>4.4</version>
+            </dependency>
+            <dependency>
+                <groupId>org.dbunit</groupId>
+                <artifactId>dbunit</artifactId>
+                <version>2.4.7</version>
+            </dependency>
+            <dependency>
+                <groupId>org.slf4j</groupId>
+                <artifactId>slf4j-api</artifactId>
+                <version>1.5.11</version>
+            </dependency>
+            <dependency>
+                <groupId>org.slf4j</groupId>
+                <artifactId>slf4j-jdk14</artifactId>
+                <version>1.5.11</version>
+            </dependency>
+
+            <dependency>
+                <groupId>javax.persistence</groupId>
+                <artifactId>persistence-api</artifactId>
+                <version>1.0</version>
+                <scope>provided</scope>
+            </dependency>
+            <dependency>
+                <groupId>javax.activation</groupId>
+                <artifactId>activation</artifactId>
+                <version>1.1</version>
+            </dependency>
+            <dependency>
+                <groupId>javax.mail</groupId>
+                <artifactId>mail</artifactId>
+                <version>1.4.1</version>
+            </dependency>
+            <dependency>
+                <groupId>javax.servlet</groupId>
+                <artifactId>servlet-api</artifactId>
+                <version>2.3</version>
+                <type>jar</type>
+                <scope>provided</scope>
+            </dependency>
+            <dependency>
+                <groupId>mysql</groupId>
+                <artifactId>mysql-connector-java</artifactId>
+                <version>5.1.12</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.derby</groupId>
+                <artifactId>derby</artifactId>
+                <version>10.5.3.0_1</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.derby</groupId>
+                <artifactId>derbyclient</artifactId>
+                <version>10.5.3.0_1</version>
+            </dependency>
+            <dependency>
+                <groupId>org.apache.derby</groupId>
+                <artifactId>derbynet</artifactId>
+                <version>10.5.3.0_1</version>
+            </dependency>
+            <dependency>
+                <groupId>quartz</groupId>
+                <artifactId>quartz</artifactId>
+                <version>1.5.1</version>
+            </dependency>
+            <dependency>
+                <groupId>jtidy</groupId>
+                <artifactId>jtidy</artifactId>
+                <version>4aug2000r7-dev</version>
+            </dependency>
+
+
+            <dependency>
+                <groupId>commons-logging</groupId>
+                <artifactId>commons-logging</artifactId>
+                <version>1.0.2</version>
+            </dependency>
+            <dependency>
+                <groupId>commons-httpclient</groupId>
+                <artifactId>commons-httpclient</artifactId>
+                <version>3.0</version>
+            </dependency>
+            <dependency>
+                <groupId>commons-beanutils</groupId>
+                <artifactId>commons-beanutils</artifactId>
+                <version>1.7.0</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-beans</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-web</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-jms</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-context</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-hibernate3</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-jpa</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-aop</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+
+            <!-- should be possible to remove the dependence on log4j -->
+            <dependency>
+                <groupId>log4j</groupId>
+                <artifactId>log4j</artifactId>
+                <version>1.2.8</version>
+            </dependency>
+            <dependency>
+                <groupId>dom4j</groupId>
+                <artifactId>dom4j</artifactId>
+                <version>1.6</version>
+                <exclusions>
+                    <exclusion>
+                        <groupId>xml-apis</groupId>
+                        <artifactId>xml-apis</artifactId>
+                    </exclusion>
+                </exclusions>
+            </dependency>
+            <dependency>
+                <groupId>net.sf.ehcache</groupId>
+                <artifactId>ehcache</artifactId>
+                <version>1.2.3</version>
+            </dependency>
+
+            <dependency>
+                <groupId>commons-email</groupId>
+                <artifactId>commons-email</artifactId>
+                <version>1.0</version>
+            </dependency>
+            <dependency>
+                <groupId>jaxen</groupId>
+                <artifactId>jaxen</artifactId>
+                <version>1.1-beta-9</version>
+                <exclusions>
+                    <exclusion>
+                        <groupId>xom</groupId>
+                        <artifactId>xom</artifactId>
+                    </exclusion>
+                    <exclusion>
+                        <groupId>xerces</groupId>
+                        <artifactId>xmlParserAPIs</artifactId>
+                    </exclusion>
+                </exclusions>
+            </dependency>
+            <dependency>
+                <groupId>jstl</groupId>
+                <artifactId>jstl</artifactId>
+                <version>1.1.2</version>
+            </dependency>
+            <dependency>
+                <groupId>taglibs</groupId>
+                <artifactId>standard</artifactId>
+                <version>1.1.2</version>
+            </dependency>
+            <dependency>
+                <groupId>jfree</groupId>
+                <artifactId>jfreechart</artifactId>
+                <version>1.0.1</version>
+            </dependency>
+            <dependency>
+                <groupId>jfree</groupId>
+                <artifactId>jcommon</artifactId>
+                <version>1.0.2</version>
+            </dependency>
+
+            <dependency>
+                <groupId>javax</groupId>
+                <artifactId>javaee-api</artifactId>
+                <version>6.0</version>
+                <scope>provided</scope>
+            </dependency>
+
+            <dependency>
+                <groupId>commons-codec</groupId>
+                <artifactId>commons-codec</artifactId>
+                <version>1.3</version>
+            </dependency>
+
+            <dependency>
+                <groupId>commons-dbcp</groupId>
+                <artifactId>commons-dbcp</artifactId>
+                <version>1.4</version>
+            </dependency>
+            <dependency>
+                <groupId>toplink.essentials</groupId>
+                <artifactId>toplink-essentials</artifactId>
+                <version>2.0-36</version>
+            </dependency>
+            <dependency>
+                <groupId>org.eclipse.persistence</groupId>
+                <artifactId>eclipselink</artifactId>
+                <version>2.0.0</version>
+                <scope>compile</scope>
+            </dependency>
+
+
+
+        </dependencies>
+    </dependencyManagement>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-release-plugin</artifactId>
+                <version>2.0</version>
+                <configuration>
+                    <autoVersionSubmodules>true</autoVersionSubmodules>
+                    <goals>javadoc:jar deploy</goals>
+                </configuration>
+            </plugin>
+            <plugin>
+                <artifactId>maven-clean-plugin</artifactId>
+                <version>2.4</version>
+                <configuration>
+                    <filesets>
+                        <fileset>
+                            <directory>.</directory>
+                            <includes>
+                                <include>derby.log</include>
+                                <include>createDDL.jdbc</include>
+                                <include>dropDDL.jdbc</include>
+                            </includes>
+                            <excludes>
+                                <exclude>**/important.log</exclude>
+                                <exclude>**/another-important.log</exclude>
+                            </excludes>
+                            <followSymlinks>false</followSymlinks>
+                        </fileset>
+                    </filesets>
+                </configuration>
+            </plugin>
+
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>jalopy-maven-plugin</artifactId>
+                <configuration>
+                    <fileFormat>UNIX</fileFormat>
+                    <convention>org.wamblee.jalopy.xml</convention>
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>1.6</source>
+                    <target>1.6</target>
+                </configuration>
+            </plugin>
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-surefire-plugin</artifactId>
+                <configuration>
+                    <includes>
+                        <include>**/*Test.java</include>
+                    </includes>
+                    <redirectTestOutputToFile>true</redirectTestOutputToFile>
+                </configuration>
+            </plugin>
+
+            <!-- Make sure other projects can use (or the test support
+           and test classes from the projects it uses. To use
+           a dependence on a test library of a project, an additinoal
+           dependence must be added with <type>test-jar</type>
+        -->
+
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-jar-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>test-jar</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>cobertura-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>clean</goal>
+                        </goals>
+                    </execution>
+                </executions>
+                <configuration>
+                    <instrumentation>
+                        <excludes> </excludes>
+                    </instrumentation>
+                </configuration>
+            </plugin>
+
+
+        </plugins>
+
+    </build>
+
+    <reporting>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-project-info-reports-plugin</artifactId>
+                <reportSets>
+                    <reportSet>
+                        <reports>
+                            <report>checkstyle</report>
+                            <report>javadoc</report>
+                            <report>dependencies</report>
+                            <report>project-team</report>
+                            <report>mailing-list</report>
+                            <report>issue-tracking</report>
+                            <report>license</report>
+                            <report>scm</report>
+                        </reports>
+                    </reportSet>
+                </reportSets>
+            </plugin>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>changes-maven-plugin</artifactId>
+                <version>2.0-beta-1</version>
+                <reportSets>
+                    <reportSet>
+                        <reports>
+                            <report>changes-report</report>
+                        </reports>
+                    </reportSet>
+                </reportSets>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-javadoc-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>surefire-report-maven-plugin</artifactId>
+            </plugin>
+            <!-- Test coverage reporting -->
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>cobertura-maven-plugin</artifactId>
+                <configuration>
+                    <formats>
+                        <format>xml</format>
+                        <format>html</format>
+                    </formats>
+                </configuration>
+            </plugin>
+
+            <!-- checkstyle -->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+                <configuration>
+                    <configLocation>config/sun_checks.xml</configLocation>
+                </configuration>
+            </plugin>
+
+            <!-- taglist -->
+            <plugin>
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>taglist-maven-plugin</artifactId>
+                <configuration>
+                    <tags>
+                        <tag>TODO</tag>
+                        <tag>@todo</tag>
+                        <tag>FIXME</tag>
+                    </tags>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </reporting>
+
+    <profiles>
+        <profile>
+            <id>release</id>
+            <activation>
+                <property>
+                    <name>performRelease</name>
+                    <value>true</value>
+                </property>
+            </activation>
+            <build>
+                <plugins>
+                    <plugin>
+                        <groupId>org.apache.maven.plugins</groupId>
+                        <artifactId>maven-gpg-plugin</artifactId>
+                        <executions>
+                            <execution>
+                                <id>sign-artifacts</id>
+                                <phase>verify</phase>
+                                <goals>
+                                    <goal>sign</goal>
+                                </goals>
+                            </execution>
+                        </executions>
+                    </plugin>
+                </plugins>
+            </build>
+            <distributionManagement>
+                <repository>
+                    <id>sonatype-nexus-staging</id>
+                    <name>Nexus Release Repository</name>
+                    <url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
+                </repository>
+            </distributionManagement>
+            
+        </profile>
+        <profile>
+            <id>all</id>
+            <activation>
+                <property>
+                    <name>!performRelease</name>
+                </property>
+            </activation>
+            <distributionManagement>
+                <repository>
+                    <id>local</id>
+                    <name>Local directory</name>
+                    <url>file:${user.home}/java/workspace/deploy</url>
+                </repository>
+            </distributionManagement>
+        </profile>
+    </profiles>
+
+
+    <properties>
+        <spring.version>2.0.8</spring.version>
+        <jmock.version>2.4.0</jmock.version>
+    </properties>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/release.sh b/tags/wamblee-utils-0.2.1/release.sh
new file mode 100755 (executable)
index 0000000..06c52cd
--- /dev/null
@@ -0,0 +1,3 @@
+mvn clean release:clean
+mvn release:prepare
+mvn -DperformRelease=true release:perform -Darguments="-Dgpg.passphrase=xxx"
diff --git a/tags/wamblee-utils-0.2.1/security/pom.xml b/tags/wamblee-utils-0.2.1/security/pom.xml
new file mode 100644 (file)
index 0000000..4d7186c
--- /dev/null
@@ -0,0 +1,101 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-security</artifactId>
+  <packaging>jar</packaging>
+  <name>/security</name>
+  <url>http://wamblee.org</url>
+  <dependencies>
+
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <type>test-jar</type>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-system-spring</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-system-spring</artifactId>
+      <type>test-jar</type>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-system-general</artifactId>
+      <type>test-jar</type>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-spring</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-spring</artifactId>
+      <type>test-jar</type>
+      <version>0.2.1</version>
+    </dependency>
+
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-hibernate-jpa</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+
+    <dependency>
+      <groupId>commons-codec</groupId>
+      <artifactId>commons-codec</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-beans</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-hibernate3</artifactId>
+      <exclusions>
+        <exclusion>
+          <groupId>org.hibernate</groupId>
+          <artifactId>hibernate</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-aop</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>javax.transaction</groupId>
+      <artifactId>transaction-api</artifactId>
+      <version>1.1</version>
+      <scope>test</scope>
+    </dependency>
+
+  </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AllOperation.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AllOperation.java
new file mode 100644 (file)
index 0000000..c76d00c
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * An superclass of all other operations. 
+ */
+public class AllOperation implements Operation {
+    
+    private static final String OPERATION = "all";
+    
+    /**
+     * Operation name. 
+     */
+    private String _name;
+    
+    /**
+     * Constructs an all operation. 
+     *
+     */
+    public AllOperation() { 
+        _name = OPERATION; 
+    }
+    
+    /**
+     * Constructs the operation, this constructor is the one that must be used
+     * by subclasses. 
+     * @param aName Name of the operation. This name must be unique among all operations. 
+     */
+    protected AllOperation(String aName) { 
+        _name = aName; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.Operation#getName()
+     */
+    public String getName() {
+        return _name; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java
new file mode 100644 (file)
index 0000000..fdee026
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.AbstractPersistent;
+import org.wamblee.usermgt.User;
+
+/**
+ * Matches any user. 
+ *
+ * @author Erik Brakkee
+ */
+public class AnyUserCondition extends AbstractPersistent implements UserCondition {
+    
+    /**
+     * Constructs the condition. 
+     *
+     */
+    public AnyUserCondition() { 
+        // Empty. 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.User)
+     */
+    public boolean matches(User aUser) {
+        return true; 
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "AnyUserCondition()"; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java
new file mode 100644 (file)
index 0000000..d7a81fd
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Authorization exception to be thrown when
+ * a resouce may not be accessed. 
+ *
+ * @author Erik Brakkee
+ */
+public class AuthorizationException extends RuntimeException {
+    
+    private Object _resource; 
+    private Operation _operation; 
+
+    public AuthorizationException(Object aResource, Operation aOperation) {
+        super("Operation '" + aOperation + "' not allowed on '" + aResource + "'");
+        _resource = aResource; 
+        _operation = aOperation; 
+    }
+    
+    public Object getResource() { 
+        return _resource; 
+    }
+    
+    public Operation getOperation() { 
+        return _operation;
+    }
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java
new file mode 100644 (file)
index 0000000..7423eab
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.apache.log4j.Logger;
+
+
+/**
+ * Inititializer class for authorization rules. This class initializes the 
+ * authorization rules in case none are present. 
+ */
+public class AuthorizationInitializer {
+    
+    private static final Logger LOGGER = Logger.getLogger(AuthorizationInitializer.class);
+
+    /**
+     * Initializes authorization rules in case none are present. 
+     * @param aService Authorization service. 
+     * @param aRules Default rules for initialization. 
+     */
+    public AuthorizationInitializer(AuthorizationService aService, AuthorizationRule[] aRules) { 
+         if ( aService.getRules().length == 0 ) { 
+             for (AuthorizationRule rule: aRules) { 
+                 LOGGER.info("Appending authorization rule " + rule);
+                 aService.appendRule(rule); 
+             }
+         }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java
new file mode 100644 (file)
index 0000000..a394910
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Represents the result of an authorization decision.
+ *
+ * @author Erik Brakkee
+ */
+public enum AuthorizationResult {
+    /**
+     * Access is granted.
+     */
+    GRANTED,
+
+    /**
+     * Access is denied.
+     */
+    DENIED,
+
+    /**
+     * Access is undecided.
+     */
+    UNDECIDED,
+
+    /**
+     * Unsupported resource.
+     */
+    UNSUPPORTED_RESOURCE
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java
new file mode 100644 (file)
index 0000000..575f4f2
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.Persistent;
+import org.wamblee.usermgt.User;
+
+/**
+ * Represents an authorization rule to determine whether an operation is allowed on a resource. 
+ *
+ * @author Erik Brakkee
+ */
+public interface AuthorizationRule extends Persistent {
+    
+    /**
+     * Returns the supported object types for which this authorization rule applies.
+     * This can be used by the authorization service for optimization.  
+     * @return Array of supported types. 
+     */
+    Class[] getSupportedTypes();
+
+    /**
+     * Determines whether an operation is allowed on a certain resource. 
+     * The rule implementation must be prepared to deal with resources for which it does
+     * not apply. In those cases it should return {@link AuthorizationResult#UNSUPPORTED_RESOURCE}. 
+     * @param aResource Resource. 
+     * @param anOperation Operation. 
+     * @param aUser Current user.  
+     * @return Authorization result. 
+     */
+    AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser);
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java
new file mode 100644 (file)
index 0000000..0115062
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.Persistent;
+
+/**
+ * Service to determine if access to a certain resource is allowed. 
+ *
+ * @author Erik Brakkee
+ */
+public interface AuthorizationService extends Persistent {
+
+    /**
+     * Checks whether an operation is allowed on a resource. 
+     * @param aResource Resource. 
+     * @param aOperation Operation. 
+     * @return Checks whether the operation is allowed on a resource. 
+     */
+    boolean isAllowed(Object aResource, Operation aOperation);
+    
+    /**
+     * Same as {@link #isAllowed(Object, Operation)} but throws a 
+     * <code>RuntimeException</code> in case access is not allowed. 
+     * @param aResource Resource to check. 
+     * @param aOperation Operation to perform.
+     * @return Resource that was checked. 
+     */
+    <T> T check(T aResource, Operation aOperation); 
+    
+    /**
+     * Gets the authorization rules. 
+     * @return Rules. 
+     */
+    AuthorizationRule[] getRules(); 
+    
+    /**
+     * Appends a new authorization rule to the end. 
+     * @param aRule Rule to append. 
+     */
+    void appendRule(AuthorizationRule aRule); 
+    
+    /**
+     * Removes a rule. 
+     * @param aRule Index of the rule to remove.  
+     */
+    void removeRule(int aIndex); 
+        
+    /**
+     * Inserts a rule. 
+     * @param aIndex Index of the position of the rule after insertion. 
+     * @param aRule Rule to insert. 
+     */
+    void insertRuleAfter(int aIndex, AuthorizationRule aRule);
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java
new file mode 100644 (file)
index 0000000..b9a96d8
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Represents an operation to create something. 
+ *
+ * @author Erik Brakkee
+ */
+public class CreateOperation extends AllOperation {
+    
+    private static final String OPERATION = "create";
+    
+    /**
+     * Constructs the operation. 
+     *
+     */
+    public CreateOperation() { 
+        super(OPERATION);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java
new file mode 100644 (file)
index 0000000..b3dc524
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.persistence.AbstractPersistent;
+import org.wamblee.usermgt.User;
+import org.wamblee.usermgt.UserAccessor;
+
+/**
+ * Default implementation of an authorization service. 
+ * To determine whether access to a resource is allowed, the service consults a number
+ * of authorization rules in a fixed order. The first rule that gives a result GRANTED or 
+ * DENIED determines the result of the evaluation. Rules that return any other result are 
+ * ignoed. If none of the rules match, than access is denied. 
+ *
+ * @author Erik Brakkee
+ */
+public class DefaultAuthorizationService extends AbstractPersistent implements AuthorizationService {
+    
+    /**
+     * List of ordered authorization rules. 
+     */
+    private List<AuthorizationRule> _rules; 
+    
+    /**
+     * User accessor used to obtain the current user. 
+     */
+    private UserAccessor _userAccessor; 
+    
+    /**
+     * Name for this instance of the authorization service. 
+     */
+    private String _name;
+    
+    /**
+     * Constructs the service. 
+     * @param aAccessor User accessor. 
+     * @param aName Name of this instance of the service. 
+     */
+    public DefaultAuthorizationService(UserAccessor aAccessor, String aName) {
+        _rules = new ArrayList<AuthorizationRule>();
+        _userAccessor = aAccessor;
+        _name = aName; 
+    }
+    
+    /**
+     * Constructs the authorization service.  
+     */
+    public DefaultAuthorizationService() {
+        _rules = new ArrayList<AuthorizationRule>();
+        _userAccessor = null;
+        _name = null; 
+    }
+    
+    /**
+     * Sets the user accessor. 
+     * @param aUserAccessor User accessor. 
+     */
+    public void setUserAccessor(UserAccessor aUserAccessor) { 
+        _userAccessor = aUserAccessor; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation)
+     */
+    public boolean isAllowed(Object aResource, Operation aOperation) {
+        User user = _userAccessor.getCurrentUser(); 
+        for (AuthorizationRule rule: _rules) { 
+            switch ( rule.isAllowed(aResource, aOperation, user)) {
+            case DENIED: { return false; } 
+            case GRANTED: { return true; }
+            }
+        }
+        return false; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation)
+     */
+    public <T> T check(T aResource, Operation aOperation) {
+        if ( !isAllowed(aResource, aOperation)) { 
+            throw new AuthorizationException(aResource, aOperation);
+        }
+        return aResource;
+    }
+    
+    protected String getName() { 
+        return _name; 
+    }
+    
+    public void setName(String aName) { 
+        _name = aName; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#getRules()
+     */
+    public AuthorizationRule[] getRules() {
+        return _rules.toArray(new AuthorizationRule[0]); 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
+     */
+    public void appendRule(AuthorizationRule aRule) {
+        _rules.add(aRule); 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, org.wamblee.security.authorization.AuthorizationRule)
+     */
+    public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
+       _rules.add(aIndex, aRule);
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
+     */
+    public void removeRule(int aIndex) {
+       _rules.remove(aIndex);
+    }
+    
+    /**
+     * For OR mapping. 
+     * @return The rules. 
+     */
+    protected List<AuthorizationRule> getMappedRules() {
+        return _rules; 
+    }
+    
+    /**
+     * For OR mapping.
+     * @param aRules The rules. 
+     */
+    protected void setMappedRules(List<AuthorizationRule> aRules) { 
+        _rules = aRules; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java
new file mode 100644 (file)
index 0000000..0a24092
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Operation registry implementation. 
+ * This implementation ignores the distinction between different types of resources
+ * and simply assumes that every operation is applicable to every type of resource. 
+ *
+ * @author Erik Brakkee
+ */
+public class DefaultOperationRegistry implements OperationRegistry {
+
+    private Map<String,Operation> _operations; 
+    
+    public DefaultOperationRegistry(Operation[] aOperations) { 
+        _operations = new TreeMap<String, Operation>();
+        for (Operation operation: aOperations) { 
+            _operations.put(operation.getName(), operation);
+        }
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.OperationRegistry#getOperations(java.lang.Class)
+     */
+    public Operation[] getOperations(Class aResourceClass) {
+        return _operations.values().toArray(new Operation[0]); 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.OperationRegistry#encode(org.wamblee.security.authorization.Operation[])
+     */
+    public String encode(Operation[] aOperations) {
+        StringBuffer buffer = new StringBuffer(); 
+        for (Operation operation: aOperations) {
+            if ( buffer.length() > 0 ) { 
+                buffer.append(',');
+            }
+            buffer.append(operation.getName());
+        }
+        return buffer.toString();
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.Class, java.lang.String)
+     */
+    public Operation[] decode(Class aResourceClass, String aOperationsString) {
+        return decode(aOperationsString); 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.String)
+     */
+    public Operation[] decode(String aOperationsString) {
+        if ( aOperationsString.length() == 0 ) { 
+            return new Operation[0]; 
+        }
+        String[] names = aOperationsString.split(",");
+        ArrayList<Operation> result = new ArrayList<Operation>(); 
+        for (String name: names) { 
+            Operation operation = _operations.get(name);
+            if ( operation == null ) { 
+                throw new IllegalArgumentException("Unknown operation '" + name + "'");
+            }
+            result.add(operation);
+        }
+        return result.toArray(new Operation[0]); 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java
new file mode 100644 (file)
index 0000000..7bdaac5
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Deletes the operation. 
+ *
+ * @author Erik Brakkee
+ */
+public class DeleteOperation extends AllOperation {
+
+    private static final String OPERATION = "delete";
+    
+    /**
+     * Constructs the operation. 
+     *
+     */
+    public DeleteOperation() { 
+        super(OPERATION);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java
new file mode 100644 (file)
index 0000000..8949fc7
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.AbstractPersistent;
+import org.wamblee.usermgt.User;
+
+/**
+ * Checks if a user against a specific group. 
+ *
+ * @author Erik Brakkee
+ */
+public class GroupUserCondition extends AbstractPersistent implements UserCondition {
+    
+    /**
+     * Group the user must be in. 
+     */
+    private String _group; 
+    
+    /**
+     * Constructs the condition. 
+     * @param aGroup Group the user must be in. 
+     */
+    public GroupUserCondition(String aGroup) {
+        _group = aGroup; 
+    }
+    
+    /**
+     * For OR mapping. 
+     *
+     */
+    protected GroupUserCondition() { 
+        _group = null; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.UserAccessor)
+     */
+    public boolean matches(User aUser) { 
+        return aUser.isInGroup(_group); 
+    }
+
+    /**
+     * @return Returns the _group.
+     */
+    protected String getGroup() {
+        return _group;
+    }
+
+    /**
+     * @param _group The _group to set.
+     */
+    protected void setGroup(String aGroup) {
+        _group = aGroup;
+    }
+
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "GroupUserCondition(group=" + _group + ")";
+    }
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java
new file mode 100644 (file)
index 0000000..e5a4d68
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.AbstractPersistent;
+
+/**
+ * Determiens if an operation is a subclass of a specified operation.
+ */
+public class IsaOperationCondition extends AbstractPersistent implements
+        OperationCondition {
+
+    /**
+     * Operation that the other operation must be a subclass of.
+     */
+    private Class<? extends Operation> _operation;
+
+    /**
+     * Constructs the condition.
+     * 
+     * @param aOperation
+     *            Operation that an operation must be an instance of.
+     */
+    public IsaOperationCondition(Class<? extends Operation> aOperation) {
+        _operation = aOperation;
+    }
+
+    /**
+     * For OR mapping.
+     * 
+     */
+    public IsaOperationCondition() {
+        _operation = null;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.OperationCondition#matches(org.wamblee.security.authorization.Operation)
+     */
+    public boolean matches(Operation aOperation) {
+        return _operation.isInstance(aOperation);
+    }
+
+    /**
+     * Gets the operation as a string. For OR mapping only.
+     * 
+     * @return Operation string.
+     */
+    protected String getOperationString() {
+        if (_operation == null) {
+            return null; 
+        }
+        return _operation.getName(); 
+    }
+
+    /**
+     * Sets the operation as a string. For OR mapping only.
+     * 
+     * @param aOperation
+     *            Operation string.
+     */
+    protected void setOperationString(String aOperation) {
+        if  (aOperation == null ) { 
+            return;
+        }
+        try { 
+            _operation = (Class<? extends Operation>)Class.forName(aOperation);
+        } catch (Exception e) { 
+            throw new IllegalArgumentException("Unknown class '" + aOperation + "'");
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "IsaOperationCondition(operation=" + _operation.getName() + ")";
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/Operation.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/Operation.java
new file mode 100644 (file)
index 0000000..2420506
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Represents an operation on a resource. 
+ * An operation should contain no state to be persisted since only the name of the
+ * operation is persisted. 
+ *
+ * @author Erik Brakkee
+ */
+public interface Operation {
+    
+    /**
+     * Gets the name of the operation. 
+     * @return Operation. 
+     */
+    String getName(); 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java
new file mode 100644 (file)
index 0000000..db6e0d0
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.Persistent;
+
+/**
+ * Checks if an operation matches a condition. 
+ *
+ * @author Erik Brakkee
+ */
+public interface OperationCondition extends Persistent {
+
+    
+    /**
+     * Determines if the operation matches. 
+     * @param aOperation Operation. 
+     * @return True iff the operation matches. 
+     */
+    boolean matches(Operation aOperation); 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java
new file mode 100644 (file)
index 0000000..bcce7c9
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+
+/**
+ * Utility to map between a list of operations and a string based
+ * on the names of the operations.   
+ *
+ * @author Erik Brakkee
+ */
+public interface OperationRegistry {
+  
+    /**
+     * Gets the supported operations for a given resource class. 
+     * @param aResourceClass Resource class. 
+     * @return Supported operations for that class. 
+     */
+    Operation[] getOperations(Class aResourceClass);
+    
+    /**
+     * Converts a number of operations to a string. 
+     * @param aOperations Operations to convert. 
+     * @return String representation of the allowed operations. 
+     */
+    String encode(Operation[] aOperations);
+    
+    /**
+     * Converts an operations string to an array of operations.
+     * @param aResourceClass Resource class.  
+     * @param aOperationsString Operations string as returned by {@link #encode(Operation[])}.
+     * @return Operations array. 
+     */
+    Operation[] decode(Class aResourceClass, String aOperationsString);
+    
+    /**
+     * Converts an operations string to an array of operations.
+     * @param aOperationsString Operations string as returned by {@link #encode(Operation[])}.
+     * @return Operations array. 
+     */
+    Operation[] decode(String aOperationsString);
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/PathCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/PathCondition.java
new file mode 100644 (file)
index 0000000..8c97017
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.Persistent;
+
+/**
+ * Checks if a path satisfies a condition. 
+ *
+ * @author Erik Brakkee
+ */
+public interface PathCondition extends Persistent {
+
+    /**
+     * Checks if the path matches the condition. 
+     * @param aPath Path to match. 
+     * @return True iff the path matches. 
+     */
+    boolean matches(String aPath); 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java
new file mode 100644 (file)
index 0000000..839fdb1
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Represents a read operation on a resource. 
+ *
+ * @author Erik Brakkee
+ */
+public class ReadOperation extends AllOperation {
+    
+    private static final String OPERATION = "read";
+    
+    /**
+     * Constructs the operation. 
+     *
+     */
+    public ReadOperation() { 
+        super(OPERATION); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java
new file mode 100644 (file)
index 0000000..5c373e8
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.AbstractPersistent;
+
+/**
+ * Condition to check whether a path  matches a given regula expression.
+ *
+ * @author Erik Brakkee
+ */
+public class RegexpPathCondition extends AbstractPersistent implements PathCondition {
+    
+    /**
+     * String the path must start with. 
+     */
+    private String _pattern; 
+    
+    /**
+     * Constructs the condition. 
+     * @param aPattern String the path must start with. 
+     */
+    public RegexpPathCondition(String aPattern) { 
+        _pattern = aPattern; 
+    }
+    
+    /**
+     * For OR mapping. 
+     *
+     */
+    protected RegexpPathCondition() { 
+        _pattern = null; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.PathCondition#matches(java.lang.String)
+     */
+    public boolean matches(String aPath) {
+        return aPath.matches(_pattern);
+    }
+
+    /**
+     * @return Returns the _path.
+     */
+    protected String getPattern() {
+        return _pattern;
+    }
+
+    /**
+     * @param aPattern The _path to set.
+     */
+    protected void setPattern(String aPattern) {
+        _pattern = aPattern;
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "RegexpCondition(pattern = '" + _pattern + "')";
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java
new file mode 100644 (file)
index 0000000..59f8627
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+
+/**
+ * Condition to check whether a path starts with a given string. 
+ *
+ * @author Erik Brakkee
+ */
+public class StartsWithPathCondition extends RegexpPathCondition {
+    
+    /**
+     * Constructs the condition. 
+     * @param aPath String the path must start with. 
+     */
+    public StartsWithPathCondition(String aPath) { 
+        super( aPath + ".*"); 
+    }
+    
+    /**
+     * For OR mapping. 
+     *
+     */
+    protected StartsWithPathCondition() { 
+        super(); 
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "StartsWithPathCondition(pattern = '" + getPattern() + "')";
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java
new file mode 100644 (file)
index 0000000..0d22d1c
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import static org.wamblee.security.authorization.AuthorizationResult.DENIED;
+import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
+import static org.wamblee.security.authorization.AuthorizationResult.UNDECIDED;
+import static org.wamblee.security.authorization.AuthorizationResult.UNSUPPORTED_RESOURCE;
+
+import org.apache.log4j.Logger;
+import org.wamblee.persistence.AbstractPersistent;
+import org.wamblee.usermgt.User;
+
+/**
+ * Utility base class for implementation of authentication rules based on the 
+ * <ul>
+ * <li> The path of the resource. To obtain the path of a resource, subclasses
+ *      must implement {@link #getResourcePath(Object)}. 
+ *      Whether a path is appropriate is determined by a 
+ *      {@link org.wamblee.security.authorization.PathCondition}. 
+ * </li>
+ * <li> The user identity with which the resource is accessed. 
+ *      Whether a user is appropriate is determined by
+ *      a {@link org.wamblee.security.authorization.UserCondition}. 
+ * </li>
+ * <li> The operation that is requested. 
+ *      Whether the operation is appropriate is determined by a 
+ *      {@link org.wamblee.security.authorization.OperationCondition}. 
+ * </li>
+ * </ul>
+ * 
+ * In case all three conditions match, the condition returns the configured
+ * result passed at construction (GRANTED or DENIED). If the resource is not
+ * of the specified type, the result is UNSUPPORTED_RESOURCE, otherwise, the
+ * result is UNDECIDED. 
+ */
+public abstract class UrlAuthorizationRule extends AbstractPersistent implements AuthorizationRule {
+    
+    private static final Logger LOGGER = Logger.getLogger(UrlAuthorizationRule.class);
+
+    /**
+     * Result that the rule will return in case there is a match. 
+     */
+    private AuthorizationResult _result;
+
+    /**
+     * A condition which specifies which users the rule is for. 
+     */
+    private UserCondition _userCondition; 
+
+    /**
+     * Path the rule applies for. 
+     */
+    private PathCondition _pathCondition;
+
+    /**
+     * Resource class that the rule applies for. 
+     */
+    private Class _resourceClass;
+    
+    /**
+     * Operation that this rule is for. 
+     */
+    private OperationCondition _operationCondition; 
+
+    /**
+     * Constructs an authorization rule. 
+     * IF the group and path match, then the provided result will be returned. 
+     * @param aResult Result of the authorization when the path and group match. 
+     * @param aUserCondition Condition to match users.  
+     * @param aPathCondition Condition to match paths with.  
+     * @param aResourceClass Supported resource class this is for.
+     * @param aOperationCondition Condition to match the operation with.  
+     */
+    protected UrlAuthorizationRule(AuthorizationResult aResult, UserCondition aUserCondition,
+            PathCondition aPathCondition, Class aResourceClass, OperationCondition aOperationCondition) {
+        if ( !aResult.equals(GRANTED) && !aResult.equals(DENIED)) {
+            throw new IllegalArgumentException("Only GRANTED or DENIED may be used: " + aResult);
+        }
+        _result = aResult;
+        _userCondition = aUserCondition; 
+        _pathCondition = aPathCondition;
+        _resourceClass = aResourceClass;
+        _operationCondition = aOperationCondition; 
+    }
+    
+    /**
+     * For OR mapping. 
+     *
+     */
+    protected UrlAuthorizationRule(Class aResourceClass) { 
+        _result = null; 
+        _userCondition = null; 
+        _pathCondition = null; 
+        _resourceClass = aResourceClass; 
+        _operationCondition = null; 
+    }
+    
+    /**
+     * For OR mapping. 
+     *
+     */
+    protected UrlAuthorizationRule() { 
+        _result = null; 
+        _userCondition = null; 
+        _pathCondition = null; 
+        _resourceClass = null; 
+        _operationCondition = null; 
+    }
+
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes()
+     */
+    public Class[] getSupportedTypes() {
+        return new Class[] { _resourceClass };
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang.Object,
+     *      org.wamblee.security.authorization.Operation)
+     */
+    public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) {
+        if ( ! _resourceClass.isInstance(aResource)) { 
+            return UNSUPPORTED_RESOURCE; 
+        }
+        String path = getResourcePath(aResource);
+        return isAllowed(path, anOperation, aUser); 
+    }
+    
+    /**
+     * Determines if the operation is allowed on the resource. 
+     * @param aPath Path of the resource. 
+     * @param aOperation Operation to be done. 
+     * @param aUser Currently logged in user or null if no user is logged in. 
+     * @return Authorization result, 
+     */
+    protected AuthorizationResult isAllowed(String aPath, Operation aOperation, User aUser) {
+        if ( ! _pathCondition.matches(aPath) ) {
+            return UNDECIDED;
+        }
+        if ( !_operationCondition.matches(aOperation) ) {
+            return UNDECIDED; 
+        }
+        if ( !_userCondition.matches(aUser)) {
+            return UNDECIDED;
+        }
+        return _result; 
+    }
+
+    /**
+     * Gets the path of the resource. 
+     * @param aResource Resource, guaranteed to be an instance of 
+     * {@link #_resourceClass}. 
+     * @return Path of the resource. 
+     */
+    protected abstract String getResourcePath(Object aResource);
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "UrlAUthorizationRule(result = " + _result + 
+           ", pathCondition = " + _pathCondition + 
+           ", userCondition = " + _userCondition +   
+           ", resourceClass = " + _resourceClass + ")";  
+    }
+    
+    /**
+     * Gets the authorization result for OR mapping. 
+     * @return Result. 
+     */
+    protected String getAuthorizationResultString() {
+        if ( _result == null ) { 
+            return null; 
+        }
+        return _result.toString(); 
+    }
+    
+    /**
+     * Sets the authorization result, for OR mapping. 
+     * @param aResult Result. 
+     */
+    protected void setAuthorizationResultString(String aResult) {
+        _result = AuthorizationResult.valueOf(aResult);
+    }
+    
+    protected String getResourceClassName() {
+        if ( _resourceClass == null ) { 
+            return "";
+        }
+        return _resourceClass.getName(); 
+    }
+    
+    protected void setResourceClassName(String aResourceClass) { 
+        try {
+            _resourceClass = Class.forName(aResourceClass);
+        } catch (ClassNotFoundException e) {
+           LOGGER.error("Cannot find resource class '" + aResourceClass + "'", e); 
+           throw new IllegalArgumentException(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * @return Returns the _operationCondition.
+     */
+    public OperationCondition getOperationCondition() {
+        return _operationCondition;
+    }
+
+    /**
+     * @param aOperationCondition The _operationCondition to set.
+     */
+    protected void setOperationCondition(OperationCondition aOperationCondition) {
+        _operationCondition = aOperationCondition;
+    }
+
+    /**
+     * @return Returns the _pathCondition.
+     */
+    public PathCondition getPathCondition() {
+        return _pathCondition;
+    }
+
+    /**
+     * @param aPathCondition The _pathCondition to set.
+     */
+    protected void setPathCondition(PathCondition aPathCondition) {
+        _pathCondition = aPathCondition;
+    }
+
+    /**
+     * @return Returns the _userCondition.
+     */
+    public UserCondition getUserCondition() {
+        return _userCondition;
+    }
+
+    /**
+     * @param aUserCondition The _userCondition to set.
+     */
+    protected void setUserCondition(UserCondition aUserCondition) {
+        _userCondition = aUserCondition;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/UserCondition.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/UserCondition.java
new file mode 100644 (file)
index 0000000..ad39877
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import org.wamblee.persistence.Persistent;
+import org.wamblee.usermgt.User;
+
+/**
+ * Condition used to match a user against a specified set of users. 
+ *
+ * @author Erik Brakkee
+ */
+public interface UserCondition extends Persistent {
+
+    /**
+     * Determines if the condition matches. 
+     * @param aUser user to check. 
+     * @return True if the condition matches, false otherwise. 
+     */
+    boolean matches(User aUser);
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java
new file mode 100644 (file)
index 0000000..212ce31
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * Represents a write operation on a resource. 
+ *
+ * @author Erik Brakkee
+ */
+public class WriteOperation extends AllOperation {
+    
+    private static final String OPERATION = "write";
+    
+    /**
+     * Constructs the operation. 
+     *
+     */
+    public WriteOperation() { 
+        super(OPERATION); 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java
new file mode 100644 (file)
index 0000000..6bd87f6
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 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.wamblee.security.authorization.hibernate;
+
+import org.wamblee.usermgt.hibernate.UsermgtHibernateMappingFiles;
+
+/**
+ * Mapping files for authorization. 
+ *
+ * @author Erik Brakkee
+ */
+public class AuthorizationMappingFiles extends UsermgtHibernateMappingFiles {
+
+    public AuthorizationMappingFiles() { 
+        super(new String[]{ "hbm/AuthorizationRule.hbm.xml", "hbm/UserCondition.hbm.xml", 
+                "hbm/AuthorizationService.hbm.xml", "hbm/OperationCondition.hbm.xml", "hbm/PathCondition.hbm.xml", 
+                "hbm/TestAuthorizationRule.hbm.xml" }); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java
new file mode 100644 (file)
index 0000000..dfe2439
--- /dev/null
@@ -0,0 +1,215 @@
+/*
+ * Copyright 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.wamblee.security.authorization.hibernate;
+
+import java.util.List;
+
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.wamblee.persistence.AbstractPersistent;
+import org.wamblee.persistence.hibernate.HibernateSupport;
+import org.wamblee.security.authorization.AuthorizationRule;
+import org.wamblee.security.authorization.AuthorizationService;
+import org.wamblee.security.authorization.DefaultAuthorizationService;
+import org.wamblee.security.authorization.Operation;
+import org.wamblee.usermgt.UserAccessor;
+
+/**
+ * Authorization service with persistent storage.
+ * This is a wrapper for {@link org.wamblee.security.authorization.DefaultAuthorizationService}
+ * which refreshes the state of the service at certain time intervals. 
+ *
+ * @author Erik Brakkee
+ */
+public class PersistentAuthorizationService extends AbstractPersistent
+        implements AuthorizationService {
+
+    /**
+     * Name of query to find the service by name.
+     */
+    private static final String FIND_QUERY = "findAuthorizationServiceByName";
+
+    /**
+     * Name of the query parameter for the service name.
+     */
+    private static final String NAME_PARAM = "name";
+
+    /**
+     * Authorization service to use.
+     */
+    private DefaultAuthorizationService _service;
+
+    /**
+     * Hibernate template to use.
+     */
+    private HibernateTemplate _template;
+
+    /**
+     * User accessor.
+     */
+    private UserAccessor _userAccessor;
+    
+    /**
+     * Name of the service. 
+     */
+    private String _name; 
+
+    /**
+     * Refresh interval in milliseconds. 
+     */
+    private final long _refreshInterval;
+    
+    /**
+     * Last refresh time. 
+     */
+    private long _lastRefreshTime; 
+
+    /**
+     * Constructs the persistent service.
+     * 
+     * @param aName
+     *            Name of the service.
+     * @param aTemplate
+     *            Hibernate template for hibernate usage.
+     * @param aAccessor
+     *            User accessor.
+     * @param aRefresh
+     *            Whether or not to refresh the state of the service at the
+     *            start of every operation.
+     */
+    public PersistentAuthorizationService(String aName,
+            HibernateTemplate aTemplate, UserAccessor aAccessor,
+            long aRefreshInterval) {
+        _template = aTemplate;
+        _refreshInterval = aRefreshInterval;
+        _lastRefreshTime = System.currentTimeMillis(); 
+        _userAccessor = aAccessor;
+        _name = aName; 
+    }
+
+    /**
+     * Initialize service if needed. 
+     */
+    private void initialize() {
+        if (_service == null) {
+            List<DefaultAuthorizationService> result = _template
+                    .findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM,
+                            _name);
+
+            if (result.size() > 1) {
+                throw new IllegalArgumentException(
+                        "Returned more than one service for name '" + _name
+                                + "' (" + result.size() + ")");
+            }
+
+            if (result.size() == 0) {
+                _service = new DefaultAuthorizationService(_userAccessor, _name);
+                _template.persist(_service);
+            } else {
+                _service = result.get(0);
+                _service.setUserAccessor(_userAccessor);
+            }
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object,
+     *      org.wamblee.security.authorization.Operation)
+     */
+    public boolean isAllowed(Object aResource, Operation aOperation) {
+        initialize();
+        refresh();
+        return _service.isAllowed(aResource, aOperation);
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation)
+     */
+    public <T> T check(T aResource, Operation aOperation) {
+        initialize();
+        refresh();
+        return _service.check(aResource, aOperation);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationService#getRules()
+     */
+    public AuthorizationRule[] getRules() {
+        initialize();
+        refresh();
+        return _service.getRules();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule)
+     */
+    public void appendRule(AuthorizationRule aRule) {
+        initialize();
+        refresh();
+        _service.appendRule(aRule);
+        save();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int)
+     */
+    public void removeRule(int aIndex) {
+        initialize();
+        refresh();
+        _service.removeRule(aIndex);
+        save();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int,
+     *      org.wamblee.security.authorization.AuthorizationRule)
+     */
+    public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
+        initialize();
+        refresh();
+        _service.insertRuleAfter(aIndex, aRule);
+        save();
+    }
+
+    /**
+     * Refreshes the state of the service through hibernate.
+     * 
+     */
+    private synchronized void refresh() {
+        long time = System.currentTimeMillis(); 
+        if ( time - _lastRefreshTime > _refreshInterval ) { 
+            _template.refresh(_service);
+            _lastRefreshTime = time; 
+        }
+    }
+
+    /**
+     * Saves any changes to the service state if necessary.
+     */
+    private void save() {
+        HibernateSupport.merge(_template, _service);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java
new file mode 100644 (file)
index 0000000..161b652
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.security.encryption;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import org.apache.commons.codec.binary.Hex;
+
+/**
+ * MD5 Hex encoder. 
+ *
+ * @author Erik Brakkee
+ */
+public class Md5HexMessageDigester implements MessageDigester {
+    
+    /**
+     * Constructs the message digester. 
+     *
+     */
+    public Md5HexMessageDigester() {
+        // Empty
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.security.MessageDigester#hash(java.lang.String)
+     */
+    public String hash(String aValue) {
+        try {
+            MessageDigest digest = MessageDigest.getInstance("MD5");
+            byte[] result = digest.digest(aValue.getBytes());
+            char[] charResult = Hex.encodeHex(result);
+            return new String(charResult);
+        } catch (NoSuchAlgorithmException e) {
+            throw new IllegalArgumentException("MD5 not supported????");
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java
new file mode 100644 (file)
index 0000000..685a4c7
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright 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.wamblee.security.encryption;
+
+/**
+ * Utility class that encapsulates a message digest method. 
+ */
+public interface MessageDigester {
+    
+    /**
+     * Computes a message digest for a value and encodes it in some way. 
+     * @param aValue Value to compute digest for. 
+     * @return Encoded digest. 
+     */
+    String hash(String aValue); 
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java
new file mode 100644 (file)
index 0000000..1a3096f
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER;
+
+import org.wamblee.security.encryption.MessageDigester;
+
+/**
+ * User set base class. 
+ */
+public abstract class AbstractUserSet implements UserSet {
+    
+    /**
+     * Password validator. 
+     */
+    private NameValidator _passwordValidator; 
+    
+    /**
+     * Password encoder. 
+     */
+    private MessageDigester _passwordEncoder; 
+
+    
+    protected AbstractUserSet(NameValidator aPasswordValidator, 
+            MessageDigester aPasswordEncoder) { 
+        _passwordValidator = aPasswordValidator;
+        _passwordEncoder = aPasswordEncoder;
+    }
+    
+    /**
+     * Sets the password validtor and encoder in the user. 
+     * @param aUser User. 
+     */
+    protected void setPasswordInfo(User aUser) { 
+        aUser.setPasswordValidator(_passwordValidator);
+        aUser.setPasswordEncoder(_passwordEncoder);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.UserSet#createUser(java.lang.String, java.lang.String, org.wamblee.usermgt.Group)
+     */
+    public User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException {
+        User user = new User(aUsername, aPassword, aGroup, _passwordValidator, _passwordEncoder);
+        if (contains(user)) {
+            throw new UserMgtException(DUPLICATE_USER, user);
+        }
+        add(user);
+        return user;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/Group.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/Group.java
new file mode 100644 (file)
index 0000000..1e7a3f5
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.io.Serializable;
+
+import org.wamblee.persistence.AbstractPersistent;
+
+/**
+ * Represents a group. 
+ *
+ * @author Erik Brakkee
+ */
+public class Group extends AbstractPersistent implements Serializable, Comparable {
+
+    /**
+     * Group name. 
+     */
+    private String _name;  
+
+    /**
+     * Constructs the group. 
+     * @param aName
+     */
+    Group(String aName) {
+        super();
+        _name = aName; 
+    }
+    
+    public Group(Group aGroup) { 
+        super(aGroup); 
+        _name = aGroup._name;
+    }
+    
+    protected Group() { 
+        super(); 
+        _name = null; 
+    }
+    
+    /**
+     * Gets the name of the group. 
+     * @return Group name. 
+     */
+    public String getName() { 
+        return _name; 
+    }
+    
+    /**
+     * Sets the group name. 
+     * @param aName Group name. 
+     */
+    void setName(String aName) {
+        _name = aName; 
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object aGroup) {
+        if ( !( aGroup instanceof Group )) { 
+            return false; 
+        }
+        return _name.equals(((Group)aGroup)._name);
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        return _name.hashCode(); 
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Comparable#compareTo(T)
+     */
+    public int compareTo(Object aGroup) {
+        return _name.compareTo(((Group)aGroup)._name);
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        return "Group(pk = " + getPrimaryKey() + ", name=" + _name + ")";
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/GroupSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/GroupSet.java
new file mode 100644 (file)
index 0000000..780d60b
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.Set;
+
+/**
+ * Represents a set of groups. A typical implemnetation would be, a readonly implementation 
+ * defined in a configuration file or a list of groups defined in a database. 
+ *
+ * @author Erik Brakkee
+ */
+public interface GroupSet {
+    
+    /**
+     * Must be called when the group has been modified to notify the group set. 
+     * @param aGroup Group that was modified. 
+     */
+    void groupModified(Group aGroup); 
+    
+    /**
+     * Finds the group by name. 
+     * @param aName Group name. 
+     * @return Group or null if not found. 
+     */
+    Group find(String aName);
+    
+    /**
+     * Determines if the group exists. 
+     * @param aGroup Group. 
+     * @return True iff the group exists. 
+     */
+    boolean contains(Group aGroup);
+    /**
+     * Adds a group. If the group already exists, the existing group set
+     * is left unchanged.   
+     * @param aGroup Group.
+     */
+    boolean add(Group aGroup);
+    
+    /**
+     * Removes a group. If the group does not exist, this method is a no-op. 
+     * @param aGroup Group to remove.
+     * @return True if the group was removed, false otherwise.  
+     */
+    boolean remove(Group aGroup);
+   
+    /**
+     * Returns the current groups. 
+     * @return Groups. 
+     */
+    Set<Group> list();
+
+    /**
+     * @return The number of groups. 
+     */
+    int size(); 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java
new file mode 100644 (file)
index 0000000..2d2cb85
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * In-memory group set implementation. 
+ *
+ * @author Erik Brakkee
+ */
+public class InMemoryGroupSet implements GroupSet {
+    
+    /**
+     * Groups. 
+     */
+    private Set<Group> _groups; 
+    
+    /**
+     * Constructs an empty group set. 
+     */
+    public InMemoryGroupSet() { 
+        _groups = new TreeSet<Group>();
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
+     */
+    public void groupModified(Group aGroup) {
+        _groups.remove(aGroup); 
+        _groups.add(aGroup);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
+     */
+    public Group find(String aName) {
+        for (Group group: _groups) { 
+            if ( group.getName().equals(aName)) { 
+                return new Group(group);
+            }
+        }
+        return null; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
+     */
+    public boolean contains(Group aGroup) {
+        return _groups.contains(aGroup);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
+     */
+    public boolean add(Group aGroup) {
+        return _groups.add(aGroup);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
+     */
+    public boolean remove(Group aGroup) {
+        return _groups.remove(aGroup);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#list()
+     */
+    public Set<Group> list() {
+        Set<Group> list = new TreeSet<Group>(); 
+        for (Group group: _groups) { 
+            list.add(new Group(group));
+        }
+        return list;
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#size()
+     */
+    public int size() {
+        return _groups.size(); 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java
new file mode 100644 (file)
index 0000000..6d25dc1
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.wamblee.security.encryption.MessageDigester;
+
+/**
+ * In-memory user set.
+ *
+ * @author Erik Brakkee
+ */
+public class InMemoryUserSet extends AbstractUserSet {
+
+    /**
+     * Users. All users in this set have their password validator and encoder set. 
+     */
+    private Set<User> _users;
+
+    /**
+     * Constructs an empty user set.
+     */
+    public InMemoryUserSet(NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
+        super(aPasswordValidator, aPasswordEncoder);
+        _users = new TreeSet<User>();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
+     */
+    public void userModified(User aUser) {
+        _users.remove(aUser);
+       setPasswordInfo(aUser); 
+        _users.add(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#find(java.lang.String)
+     */
+    public User find(String aName) {
+        for (User user : _users) {
+            if (user.getName().equals(aName)) {
+                return new User(user);
+            }
+        }
+        return null;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User)
+     */
+    public boolean add(User aUser) {
+        setPasswordInfo(aUser);
+        return _users.add(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
+     */
+    public boolean contains(User aUser) {
+        return _users.contains(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
+     */
+    public boolean remove(User aUser) {
+        return _users.remove(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#list()
+     */
+    public Set<User> list() {
+        Set<User> list = new TreeSet<User>();
+        for (User user : _users) {
+            list.add(new User(user));
+        }
+        return list;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group)
+     */
+    public Set<User> list(Group aGroup) {
+        Set<User> result = new TreeSet<User>();
+        for (User user : _users) {
+            if (user.getGroups().contains(aGroup)) {
+                result.add(new User(user));
+            }
+        }
+        return result;
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.UserSet#size()
+     */
+    public int size() {
+        return _users.size(); 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java
new file mode 100644 (file)
index 0000000..f353e3b
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.security.AccessController;
+import java.security.Principal;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+
+/**
+ * Implementation of the user accessor that retrieves user information
+ * from JAAS. 
+ *
+ * @author Erik Brakkee
+ */
+public class JaasUserAccessor implements UserAccessor {
+
+    /**
+     * User administration to use. 
+     */
+    private UserAdministration _admin;
+
+    /**
+     * Class of the JAAS user principal. 
+     */
+    private Class _userPrincipalClass;
+
+    /**
+     * Constructs user accessor. 
+     * @param aAdmin User administration. 
+     * @param aUserClassName Class name of the user principal. 
+     */
+    public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) {
+        _admin = aAdmin;
+        try {
+            _userPrincipalClass = Class.forName(aUserClassName);
+            if ( !Principal.class.isAssignableFrom(_userPrincipalClass)) {
+                throw new IllegalArgumentException("Specified class '" + aUserClassName + "' is not a subclass of '" +
+                        Principal.class.getName());
+            }
+        } catch (ClassNotFoundException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
+     */
+    public User getCurrentUser() {
+        Subject subject = Subject.getSubject(AccessController.getContext());
+        if (subject == null) {
+            return null;
+        }
+        Principal userPrincipal = getUserPrincipal(subject);
+      
+        return _admin.getUser(userPrincipal.getName());
+    }
+
+    /**
+     * Gets the user principal from the subject. 
+     * @param subject Subject. 
+     * @return User principal. 
+     * @throws IllegalArgumentException In case there is a duplicate principal or the principal was not found. 
+     */
+    private Principal getUserPrincipal(Subject subject) {
+        Set<Principal> principals = subject.getPrincipals();
+        Principal userPrincipal = null;  
+        for ( Principal principal: principals) { 
+            if ( principal.getClass().equals(_userPrincipalClass)) { 
+                if ( userPrincipal != null ) { 
+                    throw new IllegalArgumentException(
+                            "Multiple principals for class '" + _userPrincipalClass + "', subject: " + subject);                   
+                }
+                userPrincipal = principal; 
+            }
+        }
+        if ( userPrincipal == null ) { 
+            throw new IllegalArgumentException(
+                    "No user principal found for class '" + _userPrincipalClass + "', subject: " + subject);
+        }
+        return userPrincipal;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/NameValidator.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/NameValidator.java
new file mode 100644 (file)
index 0000000..f120d24
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+/**
+ * Validator of names.
+ *
+ * @author Erik Brakkee
+ */
+public interface NameValidator {
+
+    /**
+     * Validates a name. 
+     * @param aName Name
+     * @throws UserMgtException In case the name is invalid. 
+     */
+    void validate(String aName) throws UserMgtException; 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java
new file mode 100644 (file)
index 0000000..8acf115
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import org.wamblee.usermgt.UserMgtException.Reason;
+
+/**
+ * Validation of names based on a regular expression. 
+ *
+ * @author Erik Brakkee
+ */
+public class RegexpNameValidator implements NameValidator {
+    
+    /**
+     * Convenience pattern for an id. 
+     */
+    public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*";
+    
+    /**
+     * Convenience pattern for a password consisting of at least 6 characters. 
+     */
+    public static final String PASSWORD_PATTERN = ".{6}.*";
+    
+    /**
+     * Pattern to use. 
+     */
+    private String _pattern;
+    
+    /**
+     * Reason to use when validation fails. 
+     */
+    private Reason _reason; 
+    
+    /**
+     * Message to report. 
+     */
+    private String _message; 
+    
+    /**
+     * Validates a regular expression. 
+     * @param aPattern Pattern that names must comply to. 
+     * @param aReason Reason to report when validation fails. 
+     * @param aMessage Message to report. 
+     */
+    public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) { 
+        _pattern = aPattern; 
+        _reason = aReason;
+        _message = aMessage; 
+    }
+    
+    /**
+     * Convenience constructor with all string parameters. Useful for configuration 
+     * in Spring. 
+     * @param aPattern Pattern to use.
+     * @param aReason Reason. 
+     * @param aMessage Message. 
+     */
+    public RegexpNameValidator(String aPattern, String aReason, String aMessage) { 
+        this(aPattern, Reason.valueOf(aReason), aMessage);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.NameValidator#validate(java.lang.String)
+     */
+    public void validate(String aName) throws UserMgtException {
+        if ( !aName.matches(_pattern)) { 
+            throw new UserMgtException(_reason, _message); 
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/User.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/User.java
new file mode 100644 (file)
index 0000000..f239c14
--- /dev/null
@@ -0,0 +1,295 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.io.Serializable;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.wamblee.persistence.AbstractPersistent;
+import org.wamblee.security.encryption.MessageDigester;
+import org.wamblee.usermgt.UserMgtException.Reason;
+
+/**
+ * Represents a user.
+ * The methods for managing the groups of the user have package scope. 
+ * Managing the groups of the user should be done through the 
+ * {@link org.wamblee.usermgt.UserAdministration} interface. 
+ */
+public class User extends AbstractPersistent implements Serializable, Comparable {
+
+    /**
+     * User name. 
+     */
+    private String _name;
+
+    /**
+     * Password. 
+     */
+    private String _password;
+
+    /**
+     * Groups the user belongs to. 
+     */
+    private Set<Group> _groups;
+    
+    /**
+     * Password validator. 
+     */
+    private NameValidator _passwordValidator; 
+
+    /**
+     * Password encoder. 
+     */
+    private MessageDigester _passwordEncoder;
+    
+    /**
+     * Constructs the user. 
+     * @param aName User name. 
+     * @param aPassword Password. 
+     * @param aGroup Group the user belongs to.  
+     */
+    User(String aName, String aPassword, Group aGroup, NameValidator aPasswordValidator, 
+            MessageDigester aPasswordEncoder) throws UserMgtException {
+        super(); 
+        _name = aName;
+        aPasswordValidator.validate(aPassword);
+        _password = aPasswordEncoder.hash(aPassword);
+        _groups = new TreeSet<Group>(); 
+        _groups.add(aGroup);
+        _passwordValidator = aPasswordValidator;
+        _passwordEncoder = aPasswordEncoder;
+    }
+    
+    public User(User aUser) { 
+        super(aUser); 
+        _name = aUser._name;
+        _password = aUser._password;
+        _groups = new TreeSet<Group>(); 
+        for (Group group: aUser._groups) {
+            _groups.add(new Group(group)); 
+        }
+        _passwordValidator = aUser._passwordValidator; 
+        _passwordEncoder = aUser._passwordEncoder;
+    }
+    
+    User() { 
+        super(); 
+        _name = null; 
+        _password = null; 
+        _groups = null; 
+        _passwordValidator = null; 
+        _passwordEncoder = null;
+    }
+    
+    /**
+     * Sets the password validator. 
+     * @param aPasswordValidator Validator. 
+     */
+    public void setPasswordValidator(NameValidator aPasswordValidator) { 
+        _passwordValidator = aPasswordValidator;
+    }
+    
+    /**
+     * Sets the password encoder. 
+     * @param aPasswordEncoder Encoder. 
+     */
+    public void setPasswordEncoder(MessageDigester aPasswordEncoder) { 
+        _passwordEncoder = aPasswordEncoder; 
+    }
+
+    /**
+     * @return Returns the _password.
+     */
+    String getPassword() {
+        return _password;
+    }
+    
+    /**
+     * Checks the password. 
+     * @param aPassword Password to check. 
+     * @throws UserMgtException In case the password is incorrect. 
+     */
+    public void checkPassword(String aPassword) throws UserMgtException {
+        String encoded = _passwordEncoder.hash(aPassword);
+        if ( !_password.equals(encoded) ) { 
+            throw new UserMgtException(Reason.INVALID_PASSWORD, this);
+        }
+    }
+    
+    /**
+     * Changes the password. 
+     * @param aOldPassword Old password. 
+     * @param aNewPassword New password. 
+     * @throws UserMgtException In case the old password is incorrect. 
+     */
+    public void changePassword(String aOldPassword, String aNewPassword) throws UserMgtException {
+        checkPassword(aOldPassword);
+        _passwordValidator.validate(aNewPassword);
+        setPassword(aNewPassword);
+    }
+
+    /**
+     * @param aPassword
+     *            The password to set.
+     */
+    public void setPassword(String aPassword) throws UserMgtException {
+        _passwordValidator.validate(aPassword);
+        _password = _passwordEncoder.hash(aPassword);
+    }
+    
+    /**
+     * For OR mapping. 
+     * @return Password. 
+     */
+    protected String getPasswordString() { 
+        return _password;
+    }
+    
+    /**
+     * For OR mapping. 
+     * @param aPassword Password. 
+     */
+    protected void setPasswordString(String aPassword) { 
+        _password = aPassword; 
+    }
+
+    /**
+     * @return Returns the _user.
+     */
+    public String getName() {
+        return _name;
+    }
+
+    /**
+     * @param aName
+     *            The username to set.
+     */
+    void setName(String aName) {
+        _name = aName;
+    }
+
+    /**
+     * Gets the groups the user belongs to. 
+     * @return Groups.
+     */
+    public Set<Group> getGroups() {
+        Set<Group> result = new TreeSet<Group>(); 
+        result.addAll(_groups);
+        return result; 
+    }
+    
+    /**
+     * Checks whether the user belongs to the given group. 
+     * @param aGroup Group. 
+     * @return True if the user belongs to the group.
+     */
+    public boolean isInGroup(Group aGroup) {
+        return _groups.contains(aGroup);
+    }
+    
+    /**
+     * Checks whether the user belongs to the given group. 
+     * @param aGroup Group. 
+     * @return True if the user belongs to the group.
+     */
+    public boolean isInGroup(String aGroup) {
+        return _groups.contains(new Group(aGroup));
+    }
+    
+    /**
+     * Gets the group set. For OR mapping. 
+     * @return set of groups. 
+     */
+    Set<Group> getGroupSet() { 
+        return _groups;
+    }
+
+    /**
+     * Sets the groups the user belongs to, for OR mapping. 
+     * @param aGroups Groups.
+     */
+    void setGroupSet(Set<Group> aGroups) {
+        _groups = aGroups;
+    }
+
+    /**
+     * Adds the user to a group. 
+     * @param aGroup Group to add the user to.
+     * @throws UserMgtException In case the user already belongs to the group.  
+     */
+    void addGroup(Group aGroup) throws UserMgtException {
+        if (_groups.contains(aGroup)) {
+            throw new UserMgtException(Reason.USER_ALREADY_IN_GROUP, aGroup);
+        }
+        _groups.add(aGroup);
+    }
+
+    /**
+     * Removes the user from a group. 
+     * @param aGroup Group. 
+     * @throws UserMgtException In case the user does not belong to the group.
+     */
+    void removeGroup(Group aGroup) throws UserMgtException {
+        if (!_groups.contains(aGroup)) {
+            throw new UserMgtException(Reason.USER_NOT_IN_GROUP, this, aGroup);
+        }
+        if ( _groups.size() == 1 ) { 
+            throw new UserMgtException(Reason.USER_MUST_BE_IN_A_GROUP, this, aGroup); 
+        }
+        _groups.remove(aGroup);
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#equals(java.lang.Object)
+     */
+    @Override
+    public boolean equals(Object aUser) {
+        if ( !(aUser instanceof User)) {
+            return false; 
+        }
+        User user = (User)aUser; 
+        return _name.equals(user._name);
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#hashCode()
+     */
+    @Override
+    public int hashCode() {
+        return _name.hashCode(); 
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Object#toString()
+     */
+    @Override
+    public String toString() {
+        String result = "User(name=" + _name + ", password=" + _password;
+        for (Group group: _groups) { 
+            result += ", group=" + group; 
+        }
+        return result + ")"; 
+    }
+    
+    /* (non-Javadoc)
+     * @see java.lang.Comparable#compareTo(T)
+     */
+    public int compareTo(Object aUser) {
+        return _name.compareTo(((User)aUser)._name);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAccessor.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAccessor.java
new file mode 100644 (file)
index 0000000..d3dd8a9
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+/**
+ * Interface for accessing the currently logged in user. 
+ *
+ * @author Erik Brakkee
+ */
+public interface UserAccessor {
+    /**
+     * Gets the current user. 
+     * @return Currently logged in user or null if no user is found. 
+     */
+    User getCurrentUser(); 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java
new file mode 100644 (file)
index 0000000..58263eb
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.security.NoSuchAlgorithmException;
+
+import org.apache.log4j.Logger;
+
+/**
+ * User administration initializer. It populates the user administration with a
+ * number of groups and users but only in case no users exist.
+ *
+ * @author Erik Brakkee
+ */
+public class UserAdminInitializer {
+    
+    private static final Logger LOGGER = Logger.getLogger(UserAdminInitializer.class);
+    
+    /**
+     * Initializes the user administration in case no users are present.
+     * 
+     */
+    public UserAdminInitializer(UserAdministration aAdmin, String[] aUsers,
+            String[] aGroups, String[] aPasswords) throws UserMgtException, NoSuchAlgorithmException {
+        if (aUsers.length != aGroups.length
+                || aUsers.length != aPasswords.length) {
+            throw new IllegalArgumentException(
+                    "Array sizes for users, groups, and passwords differ: "
+                            + aUsers.length + "," + aGroups.length + ","
+                            + aPasswords.length);
+
+        }
+        if (aAdmin.getUserCount() == 0) {
+            initialize(aAdmin, aUsers, aGroups, aPasswords);
+        }
+       
+    }
+
+    /**
+     * Adds the specified users and groups to the user administration. 
+     * @param aAdmin User administration. 
+     * @param aUsers Users. 
+     * @param aGroups Groups. 
+     * @param aPasswords Passwords. 
+     * @throws UserMgtException In case of a problem creating users or groups. 
+     */
+    private void initialize(UserAdministration aAdmin, String[] aUsers,
+            String[] aGroups, String[] aPasswords) throws UserMgtException {
+        for (int i = 0; i < aUsers.length; i++) {
+            String user = aUsers[i];
+            String group = aGroups[i];
+            String password = aPasswords[i];
+            
+            if (aAdmin.getUser(user) == null) {
+                // must create user.
+                Group groupObj = aAdmin.getGroup(group);
+                if (groupObj == null) {
+                    // must create group
+                    LOGGER.info("Creating group: " + group);
+                    groupObj = aAdmin.createGroup(group);
+                }
+                assert groupObj != null; 
+                
+                LOGGER.info("Creating user: " + user + " password: " + password);
+                aAdmin.createUser(user, password, groupObj);
+            }
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdministration.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdministration.java
new file mode 100644 (file)
index 0000000..1ce6fbf
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.Set;
+
+/**
+ * Interface for user administration. Manages the users and groups. 
+ *
+ * @author Erik Brakkee
+ */
+public interface UserAdministration {
+    
+    /**
+     * Creates a new user. 
+     * @param aUser Username. 
+     * @param aPassword Password. 
+     * @param aGroup Group. 
+     * @return User. 
+     * @throws UserMgtException In case there is a conflict with an existing user. 
+     */
+    User createUser(String aUser, String aPassword, Group aGroup) throws UserMgtException; 
+    
+    /**
+     * Creates a new group. 
+     * @param aName Group name. 
+     * @return Group
+     * @throws UserMgtException In case there is a conflict with an existing group. 
+     */
+    Group createGroup(String aName) throws UserMgtException;
+    
+    /** 
+     * @return Number of users. 
+     */
+    int getUserCount(); 
+    
+    /**
+     * @return Number of groups. 
+     */
+    int getGroupCount(); 
+    
+    /**
+     * Must be called when the user is modified. 
+     * @param aUser User.
+     */
+    void userModified(User aUser);
+    
+    /**
+     * Must be called when the group is modified. 
+     * @param aGroup Group. 
+     */
+    void groupModified(Group aGroup); 
+
+    /**
+     * Gets the user for a given name. 
+     * @param aName User name. 
+     * @return User or null if not found.   
+     */
+    User getUser(String aName); 
+    
+    /**
+     * Gets the group for a given group name. 
+     * @param aName Group name. 
+     * @return Group or null if not found. 
+     */
+    Group getGroup(String aName); 
+    
+    /**
+     * Get the users. 
+     * @return All known users. 
+     */
+    Set<User> getUsers(); 
+    
+    /**
+     * Gets the users for a given group. 
+     * @param aGroup Group. 
+     * @return Set of users (always non-null).
+     */
+    Set<User> getUsers(Group aGroup);
+    
+    /**
+     * Gets all known groups. 
+     * @return Groups. 
+     */
+    Set<Group> getGroups();
+    
+    /**
+     * Renames a user. 
+     * @param aUser User object for which user name must be changed. 
+     * @param aUserName New user name. 
+     * @throws UserMgtException In case the user is not known or the new user 
+     *    name is already in use by another user.  
+     */
+    void renameUser(User aUser, String aUserName) throws UserMgtException;
+    
+    /**
+     * Renames a group. 
+     * @param aGroup Group to rename. 
+     * @param aGroupName New name for the group. 
+     * @throws UserMgtException In case the new group name is already used by 
+     *    another group of if the existing group is unknown.  
+     */
+    void renameGroup(Group aGroup, String aGroupName) throws UserMgtException;
+    
+    /**
+     * Removes the user. 
+     * @param aUser User to remove. 
+     * @throws UserMgtException In case the user does not exist.  
+     */
+    void removeUser(User aUser) throws UserMgtException;
+    
+    /**
+     * Removes the group. 
+     * @param aGroup Group to remove. 
+     * @throws UserMgtException In case there are still users that are in the given group. 
+     */
+    void removeGroup(Group aGroup) throws UserMgtException;
+    
+    /**
+     * Adds a user to a group. 
+     * @param aUser User. 
+     * @param aGroup Group. 
+     * @throws UserMgtException In case the user or group or not known or if the user 
+     *   is already part of the group. 
+     */
+    void addUserToGroup(User aUser, Group aGroup) throws UserMgtException;
+    
+    /**
+     * Removes a user from a group. 
+     * @param aUser User
+     * @param aGroup Group
+     * @throws UserMgtException In case the user or group are unknown or if the user 
+     *    is not part of the group. 
+     */
+    void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException; 
+}
+
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java
new file mode 100644 (file)
index 0000000..dceca93
--- /dev/null
@@ -0,0 +1,289 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_GROUP;
+import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER;
+import static org.wamblee.usermgt.UserMgtException.Reason.GROUP_STILL_OCCUPIED;
+import static org.wamblee.usermgt.UserMgtException.Reason.TRIVIAL_RENAME;
+import static org.wamblee.usermgt.UserMgtException.Reason.UNKNOWN_GROUP;
+import static org.wamblee.usermgt.UserMgtException.Reason.UNKNOWN_USER;
+
+import java.util.Set;
+
+/**
+ * Administration of users and groups.
+ *
+ * @author Erik Brakkee
+ */
+public class UserAdministrationImpl implements UserAdministration {
+   
+    /**
+     * All known users.
+     */
+    private UserSet _users;
+
+    /**
+     * All known groups.
+     */
+    private GroupSet _groups;
+    
+    /**
+     * Validator for user names. 
+     */
+    private NameValidator _userValidator;
+    
+    /**
+     * Validator for group names. 
+     */
+    private NameValidator _groupValidator;
+    
+    /**
+     * Constructs empty user administration.
+     * 
+     */
+    public UserAdministrationImpl(UserSet aUsers, GroupSet aGroups, NameValidator aUserValidator, 
+              NameValidator aGroupValidator) { 
+        _users = aUsers;
+        _groups = aGroups;
+        _userValidator = aUserValidator;
+        _groupValidator = aGroupValidator;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#createUser(java.lang.String,
+     *      java.lang.String)
+     */
+    public User createUser(String aUser, String aPassword, Group aGroup)
+            throws UserMgtException {
+        _userValidator.validate(aUser);
+        checkGroup(aGroup);
+        User user = _users.createUser(aUser, aPassword, aGroup);
+        return new User(user);
+    }
+    
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#createGroup(java.lang.String)
+     */
+    public Group createGroup(String aName) throws UserMgtException {
+        _groupValidator.validate(aName);
+        Group group = new Group(aName);
+        if (_groups.contains(group)) {
+            throw new UserMgtException(DUPLICATE_GROUP, group);
+        }
+        _groups.add(group);
+        return new Group(group);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#userModified(org.wamblee.usermgt.User)
+     */
+    public void userModified(User aUser) {
+        _users.userModified(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt.Group)
+     */
+    public void groupModified(Group aGroup) {
+        _groups.groupModified(aGroup);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#getUser(java.lang.String)
+     */
+    public User getUser(String aName) {
+        return _users.find(aName);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#getGroup(java.lang.String)
+     */
+    public Group getGroup(String aName) {
+        return _groups.find(aName);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#getUsers()
+     */
+    public Set<User> getUsers() {
+        return _users.list();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group)
+     */
+    public Set<User> getUsers(Group aGroup) {
+        return _users.list(aGroup);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#getGroups()
+     */
+    public Set<Group> getGroups() {
+        return _groups.list();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#removeUser(org.wamblee.usermgt.User)
+     */
+    public void removeUser(User aUser) throws UserMgtException {
+        checkUser(aUser);
+        _users.remove(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#removeGroup(org.wamblee.usermgt.Group)
+     */
+    public void removeGroup(Group aGroup) throws UserMgtException {
+        checkGroup(aGroup);
+        if (getUsers(aGroup).size() > 0) {
+            throw new UserMgtException(GROUP_STILL_OCCUPIED, aGroup);
+        }
+        _groups.remove(aGroup);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#renameUser(org.wamblee.usermgt.User,
+     *      java.lang.String)
+     */
+    public void renameUser(User aUser, String aUserName)
+            throws UserMgtException {
+        checkUser(aUser);
+        if (aUser.getName().equals(aUserName)) {
+            throw new UserMgtException(TRIVIAL_RENAME, aUser);
+        }
+        if (_users.find(aUserName) != null) {
+            throw new UserMgtException(DUPLICATE_USER, aUser);
+        }
+        _userValidator.validate(aUserName);
+        // we are modifying the user so we should re-insert it into the set
+        // after renaming it.
+        _users.remove(aUser);
+        aUser.setName(aUserName);
+        _users.add(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#renameGroup(org.wamblee.usermgt.Group,
+     *      java.lang.String)
+     */
+    public void renameGroup(Group aGroup, String aGroupName)
+            throws UserMgtException {
+        checkGroup(aGroup);
+        if (aGroup.getName().equals(aGroupName)) {
+            throw new UserMgtException(TRIVIAL_RENAME, aGroup);
+        }
+        if (_groups.find(aGroupName) != null) {
+            throw new UserMgtException(DUPLICATE_GROUP, aGroup);
+        }
+        _groupValidator.validate(aGroupName);
+        // we are renaming the group so we should re-insert it into the set
+        // after renaming it.
+        _groups.remove(aGroup);
+        aGroup.setName(aGroupName);
+        _groups.add(aGroup);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#addUserToGroup(org.wamblee.usermgt.User,
+     *      org.wamblee.usermgt.Group)
+     */
+    public void addUserToGroup(User aUser, Group aGroup)
+            throws UserMgtException {
+        checkUser(aUser);
+        checkGroup(aGroup);
+        aUser.addGroup(aGroup);
+        _users.userModified(aUser);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministration#removeUserFromGroup(org.wamblee.usermgt.User,
+     *      org.wamblee.usermgt.Group)
+     */
+    public void removeUserFromGroup(User aUser, Group aGroup)
+            throws UserMgtException {
+        checkUser(aUser);
+        checkGroup(aGroup);
+        aUser.removeGroup(aGroup);
+        _users.userModified(aUser);
+    }
+
+    /**
+     * @param aUser
+     * @throws UserMgtException
+     */
+    private void checkUser(User aUser) throws UserMgtException {
+        if (!_users.contains(aUser)) {
+            throw new UserMgtException(UNKNOWN_USER, aUser);
+        }
+    }
+
+    /**
+     * @param aGroup
+     * @throws UserMgtException
+     */
+    private void checkGroup(Group aGroup) throws UserMgtException {
+        if (!_groups.contains(aGroup)) {
+            throw new UserMgtException(UNKNOWN_GROUP, aGroup);
+        }
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.UserAdministration#getUserCount()
+     */
+    public int getUserCount() {
+        return _users.size(); 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.UserAdministration#getGroupCount()
+     */
+    public int getGroupCount() {
+        return _groups.size(); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java
new file mode 100644 (file)
index 0000000..fb3378c
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeMap;
+
+import net.sf.ehcache.Ehcache;
+
+import org.hibernate.SessionFactory;
+import org.wamblee.cache.EhCache;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.spring.SpringComponent;
+
+public class UserGroupRepositoryComponent extends SpringComponent {
+
+    public UserGroupRepositoryComponent(String aName) { 
+        super(aName, new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" } , 
+                createProvided(), createRequired()); 
+        
+    }
+
+    private static Map<RequiredInterface, String> createRequired() {
+        Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+        required.put(new DefaultRequiredInterface("sessionFactory", SessionFactory.class), "sessionFactory");
+        return required;
+    }
+
+    private static Map<String, ProvidedInterface> createProvided() {
+        Map<String,ProvidedInterface> provided = new HashMap<String,ProvidedInterface>();
+        provided.put("userCache", new DefaultProvidedInterface("cache", EhCache.class));
+        provided.put(UserSet.class.getName(), new DefaultProvidedInterface("userset", UserSet.class));
+        provided.put(GroupSet.class.getName(), new DefaultProvidedInterface("groupset", GroupSet.class));
+        return provided; 
+    }
+    
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserMgtException.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserMgtException.java
new file mode 100644 (file)
index 0000000..6a96e61
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.EnumMap;
+
+/**
+ * User management exception. 
+ *
+ * @author Erik Brakkee
+ */
+public class UserMgtException extends Exception {
+    
+    static final long serialVersionUID = 5585349754997507529L; 
+    
+    /**
+     * Possible causes for the exception. 
+     *
+     */
+    public enum Reason { 
+        UNKNOWN_USER, 
+        UNKNOWN_GROUP,
+        DUPLICATE_USER, 
+        DUPLICATE_GROUP, 
+        USER_ALREADY_IN_GROUP,
+        USER_NOT_IN_GROUP,
+        TRIVIAL_RENAME,
+        INVALID_PASSWORD, 
+        GROUP_STILL_OCCUPIED, 
+        USER_MUST_BE_IN_A_GROUP,
+        INVALID_USERNAME,
+        INVALID_GROUPNAME
+    }
+   
+    /**
+     * Mapping of enum to exception message text. 
+     */
+    private static final EnumMap<Reason,String> MESSAGES = new EnumMap<Reason,String>(Reason.class);
+    
+    static {
+        MESSAGES.put(Reason.UNKNOWN_USER, "Unknown user");
+        MESSAGES.put(Reason.UNKNOWN_GROUP, "Unknown group");
+        MESSAGES.put(Reason.DUPLICATE_USER, "Duplicate user");
+        MESSAGES.put(Reason.DUPLICATE_GROUP, "Duplicate group");
+        MESSAGES.put(Reason.USER_ALREADY_IN_GROUP, "User already in group");
+        MESSAGES.put(Reason.USER_NOT_IN_GROUP, "User not in group");
+        MESSAGES.put(Reason.TRIVIAL_RENAME, "Trivial rename");
+        MESSAGES.put(Reason.INVALID_PASSWORD, "Invalid password");
+        MESSAGES.put(Reason.GROUP_STILL_OCCUPIED, "Group still occupied");
+        MESSAGES.put(Reason.USER_MUST_BE_IN_A_GROUP, "User must be in at least one group");
+        MESSAGES.put(Reason.INVALID_USERNAME, "Invalid user name");
+        MESSAGES.put(Reason.INVALID_GROUPNAME, "Invalid group name");
+    }
+    
+    /**
+     * Cause of the exception. 
+     */
+    private Reason _cause; 
+    
+    /**
+     * User or null if no user is relevant for the problem. 
+     */
+    private User _user; 
+    
+    /**
+     * Group or null if no group is relevant for the problem. 
+     */
+    private Group _group; 
+
+    public UserMgtException(Reason aCause, String aMessage) {
+        super(MESSAGES.get(aCause) + ": " + aMessage);
+        _cause = aCause; 
+    }
+    
+    public UserMgtException(Reason aCause, User aUser) {
+        this(aCause, "for user '" + aUser.getName() + "'");
+        _user = aUser; 
+    }
+    
+    public UserMgtException(Reason aCause, Group aGroup) {
+        this(aCause, "for group '" + aGroup.getName() + "'");
+        _group = aGroup; 
+    }
+    
+    public UserMgtException(Reason aCause, User aUser, Group aGroup) {
+        this(aCause, "for user '" + aUser.getName() + "' and group '" + aGroup.getName() + "'");
+        _user = aUser; 
+        _group = aGroup; 
+    }
+
+    /**
+     * Gets the cause of the problem. 
+     * @return Cause. 
+     */
+    public Reason getReason() {
+        return _cause; 
+    }
+    
+    /**
+     * Gets the user for which the problem occurred. 
+     * @return User or null if not applicable.  
+     */
+    public User getUser() {
+        return _user; 
+    }
+    
+    /**
+     * Gets the group for which the problem occured. 
+     * @return Group or null if not applicable. 
+     */
+    public Group getGroup() {
+        return _group;
+    }   
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/UserSet.java
new file mode 100644 (file)
index 0000000..ac3f5a7
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.Set;
+
+/**
+ * Represents a set of users.
+ * Typical implementations would be an implementation based on a static configuration file or 
+ * an implementation backed by a database.  
+ *
+ * @author Erik Brakkee
+ */
+public interface UserSet {
+    
+    /**
+     * Creates a user. 
+     * @param aUsername User name. 
+     * @param aPassword Password. 
+     * @param aGroup Group.
+     * @return New user.  
+     * @throws UserMgtException In case the user cannot be created. 
+     */ 
+    User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException; 
+    
+    /**
+     * Must be called whenever a user object has been modified to notify the
+     * user set.  
+     * @param aUser Modified user. 
+     */
+    void userModified(User aUser); 
+    
+    /**
+     * Finds  user. 
+     * @param aName Username. 
+     * @return User or null if not found. 
+     */
+    User find(String aName);
+    
+    /**
+     * Checks if a user exists. 
+     * @param aUser User. 
+     * @return True iff the user exists. 
+     */
+    boolean contains(User aUser); 
+    
+    /**
+     * Adds a user. If the user already exists, the user details are updated with that
+     * of the specified user object. 
+     * @param aUser User to add. 
+     */
+    boolean add(User aUser);
+    
+    /**
+     * Removes a user. If the user does not exist, nothing happens. 
+     * @param aUser
+     */
+    boolean remove(User aUser);
+    
+    /**
+     * Lists the current users. 
+     * @return Users. 
+     */
+    Set<User> list(); 
+    
+    /**
+     * Lists the users belonging to a particular group. 
+     * @param aGroup Group. 
+     * @return Groups. 
+     */
+    Set<User> list(Group aGroup);
+
+    /**
+     * 
+     * @return The number of users. 
+     */
+    int size(); 
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java
new file mode 100644 (file)
index 0000000..150a844
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.io.IOException;
+
+import javax.sql.DataSource;
+
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.wamblee.cache.EhCache;
+import org.wamblee.security.authorization.AuthorizationService;
+import org.wamblee.security.authorization.hibernate.AuthorizationMappingFiles;
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.components.ORMappingConfig;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.component.HibernateComponent;
+import org.wamblee.usermgt.UserAccessor;
+import org.wamblee.usermgt.UserAdministration;
+import org.wamblee.usermgt.UserGroupRepositoryComponent;
+
+public class AuthorizationComponent extends DefaultContainer {
+
+    private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface(
+            "transactionManager", PlatformTransactionManager.class);
+    private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface(
+            "hibernateTemplate", HibernateTemplate.class);
+    private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface(
+            "authorizationService", AuthorizationService.class);
+
+    public AuthorizationComponent(String aName, boolean aExposeInternals)
+            throws IOException {
+        super(aName);
+       
+        ObjectConfiguration authConfig = new ObjectConfiguration(AuthorizationMappingFiles.class);
+        authConfig.getSetterConfig().initAllSetters();
+        addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig); 
+
+        Component<?> hibernate = new HibernateComponent("hibernate");
+        addComponent(hibernate);
+
+        Component<?> authorization = new AuthorizationLightComponent("authorization");
+        addComponent(authorization);
+
+        addRequiredInterface(new DefaultRequiredInterface("datasource", DataSource.class));
+        addRequiredInterface(new DefaultRequiredInterface("userAccessor",
+                UserAccessor.class));
+        addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class));
+
+        if (aExposeInternals) {
+            addProvidedInterface(TRANSACTION_MGR);
+            addProvidedInterface(HIBERNATE_TEMPLATE);
+        }
+        addProvidedInterface(AUTHORIZATION_SERVICE);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java
new file mode 100644 (file)
index 0000000..e7b0c96
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.wamblee.security.authorization.AuthorizationService;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.spring.SpringComponent;
+import org.wamblee.usermgt.GroupSet;
+import org.wamblee.usermgt.UserAccessor;
+import org.wamblee.usermgt.UserAdministration;
+import org.wamblee.usermgt.UserSet;
+
+/**
+ * Light version of the user administration component that requires external
+ * datasource, and userset and group set components, as well as an external
+ * hibernate session factory.
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class AuthorizationLightComponent extends SpringComponent {
+
+    public AuthorizationLightComponent(String aName) {
+        super(
+                aName,
+                new String[] { "spring/org.wamblee.security.authorization.xml" },
+                createProvided(), createRequired());
+    }
+
+    private static Map<RequiredInterface, String> createRequired() {
+        Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+        required.put(new DefaultRequiredInterface("userArccessor",
+                UserAccessor.class), UserAccessor.class.getName());
+        required.put(new DefaultRequiredInterface("hibernateTemplate",
+                HibernateTemplate.class), HibernateTemplate.class.getName());
+        return required;
+    }
+
+    private static Map<String, ProvidedInterface> createProvided() {
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put(AuthorizationService.class.getName(),
+                new DefaultProvidedInterface(AuthorizationService.class
+                        .getName(), AuthorizationService.class));
+        return provided;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java
new file mode 100644 (file)
index 0000000..957ee44
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.wamblee.persistence.hibernate.HibernateSupport;
+import org.wamblee.usermgt.Group;
+import org.wamblee.usermgt.GroupSet;
+
+/**
+ * Set of groups backed by the database. 
+ *
+ * @author Erik Brakkee
+ */
+public class HibernateGroupSet extends HibernateSupport implements GroupSet {
+    
+    
+    private static final String QUERY_FIND_BY_NAME = "findGroupByName";
+    
+    private static final String PARAM_NAME = "name";
+    
+    private static final String QUERY_COUNT_GROUPS = "countGroups";
+    
+    public HibernateGroupSet() {
+        // Empty
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group)
+     */
+    public void groupModified(Group aGroup) {
+        assert aGroup.getPrimaryKey() != null; 
+        super.merge(aGroup);        
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#find(java.lang.String)
+     */
+    public Group find(String aName) {
+        List list = getHibernateTemplate().findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+        if ( list.size() > 1 ) { 
+            throw new RuntimeException("More than one group with the same name '" + aName + "'");
+        }
+        if ( list.size() == 0 ) { 
+            return null; 
+        }
+        return new Group((Group)list.get(0));
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group)
+     */
+    public boolean contains(Group aGroup) {
+        return find(aGroup.getName()) != null; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group)
+     */
+    public boolean add(Group aGroup) {
+        assert aGroup.getPrimaryKey() == null; 
+        if ( contains(aGroup) ) { 
+            return false; 
+        }
+        super.merge(aGroup);
+        return true; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group)
+     */
+    public boolean remove(Group aGroup) {
+        assert aGroup.getPrimaryKey() != null; 
+        if ( !contains(aGroup)) { 
+            return false; 
+        }
+        Group group = (Group) getHibernateTemplate().merge(aGroup); 
+        getHibernateTemplate().delete(group);
+        aGroup.setPrimaryKey(null); 
+        aGroup.setPersistedVersion(-1);
+        return true; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#list()
+     */
+    public Set<Group> list() {
+        Set<Group> groups = new TreeSet<Group>(); 
+        List<Group> list = getHibernateTemplate().loadAll(Group.class);
+        for (Group group: list) { 
+            groups.add(new Group(group));
+        }
+        return groups; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.GroupSet#size()
+     */
+    public int size() {
+        Long result = (Long) getHibernateTemplate().findByNamedQuery(QUERY_COUNT_GROUPS).get(0);
+        return result.intValue(); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java
new file mode 100644 (file)
index 0000000..8bc1db5
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.hibernate.SessionFactory;
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.wamblee.cache.Cache;
+import org.wamblee.persistence.hibernate.HibernateSupport;
+import org.wamblee.security.encryption.MessageDigester;
+import org.wamblee.usermgt.AbstractUserSet;
+import org.wamblee.usermgt.Group;
+import org.wamblee.usermgt.NameValidator;
+import org.wamblee.usermgt.User;
+
+/**
+ * User set backed by the database.
+ *
+ * @author Erik Brakkee
+ */
+public class HibernateUserSet extends AbstractUserSet {
+
+    private static final String QUERY_FIND_BY_NAME = "findUserByName";
+
+    private static final String QUERY_FIND_BY_GROUP_NAME = "findUserByGroupName";
+
+    private static final String PARAM_NAME = "name";
+    
+    private static final String QUERY_COUNT_USERS = "countUsers"; 
+
+    /**
+     * Cache of users. Every user in the cache has its password validator and encoder set.  
+     */
+    private Cache<String, User> _cache;
+    
+    /** 
+     * Spring hibernate support. 
+     */
+    private HibernateSupport _hibernateSupport; 
+
+    /**
+     * Constructs a user set backed by the database.
+     * @param aCache User cache to use. 
+     */
+    public HibernateUserSet(Cache<String,User> aCache, 
+            NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) {
+        super(aPasswordValidator, aPasswordEncoder);
+        _cache = aCache;
+        _hibernateSupport = new HibernateSupport();
+    }
+    
+    /**
+     * Sets the session factory. 
+     * @param aFactory Session factory. 
+     */
+    public void setSessionFactory(SessionFactory aFactory) { 
+        _hibernateSupport.setSessionFactory(aFactory);
+    }
+    
+    /**
+     * Gets the hibernate template. 
+     * @return Hibernate template. 
+     */
+    private HibernateTemplate getHibernateTemplate() { 
+        return _hibernateSupport.getHibernateTemplate();
+    }
+   
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User)
+     */
+    public void userModified(User aUser) {
+        assert aUser.getPrimaryKey() != null;
+        _hibernateSupport.merge(aUser);
+        _cache.remove(aUser.getName());
+        setPasswordInfo(aUser);
+        _cache.put(aUser.getName(), new User(aUser));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#find(java.lang.String)
+     */
+    public User find(String aName) {
+        User user = _cache.get(aName);
+        if (user != null) {
+            return user;
+        }
+        List result = getHibernateTemplate().findByNamedQueryAndNamedParam(
+                QUERY_FIND_BY_NAME, PARAM_NAME, aName);
+        if (result.size() > 1) {
+            throw new RuntimeException(
+                    "Implementation problem, more than one user with the same name!");
+        }
+        if (result.size() == 0) {
+            return null;
+        }
+        user = (User) result.get(0);
+        setPasswordInfo(user);
+        _cache.put(aName, user);
+        return new User(user);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User)
+     */
+    public boolean contains(User aUser) {
+        return find(aUser.getName()) != null;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User)
+     */
+    public boolean add(User aUser) {
+        assert aUser.getPrimaryKey() == null;
+        if (contains(aUser)) {
+            return false;
+        }
+        getHibernateTemplate().saveOrUpdate(aUser);
+        setPasswordInfo(aUser);
+        _cache.put(aUser.getName(), aUser);
+        return true;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User)
+     */
+    public boolean remove(User aUser) {
+        assert aUser.getPrimaryKey() != null;
+        if (!contains(aUser)) {
+            return false;
+        }
+        User user = (User) getHibernateTemplate().merge(aUser);
+        getHibernateTemplate().delete(user);
+        aUser.setPersistedVersion(-1);
+        aUser.setPrimaryKey(null);
+        _cache.remove(aUser.getName());
+        return true;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#list()
+     */
+    public Set<User> list() {
+        Set<User> users = new TreeSet<User>();
+        List<User> list = getHibernateTemplate().loadAll(User.class);
+        for (User user : list) {
+            setPasswordInfo(user);
+            users.add(new User(user));
+        }
+        return users;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group)
+     */
+    public Set<User> list(Group aGroup) {
+        Set<User> users = new TreeSet<User>();
+        List<User> list = getHibernateTemplate().findByNamedQueryAndNamedParam(
+                QUERY_FIND_BY_GROUP_NAME, PARAM_NAME, aGroup.getName());
+        for (User user : list) {
+            setPasswordInfo(user);
+            users.add(new User(user));
+        }
+        return users;
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.UserSet#size()
+     */
+    public int size() {
+        Long result = (Long)getHibernateTemplate().findByNamedQuery(QUERY_COUNT_USERS).get(0);
+        return result.intValue(); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java
new file mode 100644 (file)
index 0000000..66e3850
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.io.IOException;
+
+import javax.sql.DataSource;
+
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.wamblee.cache.EhCache;
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.components.ORMappingConfig;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.component.HibernateComponent;
+import org.wamblee.usermgt.UserAdministration;
+import org.wamblee.usermgt.UserGroupRepositoryComponent;
+
+public class UserAdministrationComponent extends DefaultContainer {
+
+    private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface(
+            "transactionManager", PlatformTransactionManager.class);
+    private ProvidedInterface USER_CACHE = new DefaultProvidedInterface(
+            "userCache", EhCache.class);
+    private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface(
+            "hibernateTemplate", HibernateTemplate.class);
+    private ProvidedInterface USER_MGT = new DefaultProvidedInterface(
+            "usermgt", UserAdministration.class);
+
+    public UserAdministrationComponent(String aName, boolean aExposeInternals)
+            throws IOException {
+        super(aName);
+        
+        ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); 
+        mappingFilesConfig.getSetterConfig().initAllSetters();
+        addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig);
+
+        Component<?> _hibernate = new HibernateComponent("hibernate");
+        addComponent(_hibernate);
+
+        Component<?> _repository = new UserGroupRepositoryComponent("usersgroups");
+        addComponent(_repository);
+
+        Component<?> _usermgt = new UserAdministrationLightComponent("usermgtlight");
+        addComponent(_usermgt);
+
+        addRequiredInterface(new DefaultRequiredInterface("datasource",
+                DataSource.class));
+        addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class));
+
+        if (aExposeInternals) {
+            addProvidedInterface(TRANSACTION_MGR);
+            addProvidedInterface(USER_CACHE);
+            addProvidedInterface(HIBERNATE_TEMPLATE);
+        }
+        addProvidedInterface(USER_MGT);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java
new file mode 100644 (file)
index 0000000..1a06ae7
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.spring.SpringComponent;
+import org.wamblee.usermgt.GroupSet;
+import org.wamblee.usermgt.UserAdministration;
+import org.wamblee.usermgt.UserSet;
+
+/**
+ * Light version of the user administration component that requires external
+ * datasource, and userset and group set components, as well as an external
+ * hibernate session factory. 
+ * @author Erik Brakkee
+ *
+ */
+public class UserAdministrationLightComponent extends SpringComponent {
+
+    public UserAdministrationLightComponent(String aName) { 
+        super(aName, new String[] { "spring/org.wamblee.security.usermgt.xml" },
+                createProvided(), createRequired() );    
+    }
+
+    private static Map<RequiredInterface, String> createRequired() {
+        Map<RequiredInterface, String> required = new HashMap<RequiredInterface,String>();
+        required.put(new DefaultRequiredInterface("userSet", UserSet.class), UserSet.class.getName());
+        required.put(new DefaultRequiredInterface("groupSet", GroupSet.class), GroupSet.class.getName());
+        return required; 
+    }
+
+    private static Map<String, ProvidedInterface> createProvided() {
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put(UserAdministration.class.getName(), new DefaultProvidedInterface("org.wamblee.usermgt.UserAdministration",
+                UserAdministration.class));
+        return provided;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java b/tags/wamblee-utils-0.2.1/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java
new file mode 100644 (file)
index 0000000..8d523c2
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.util.Collections;
+
+import org.wamblee.persistence.hibernate.HibernateMappingFiles;
+
+/**
+ * Hibernate mapping files for user management. 
+ *
+ * @author Erik Brakkee
+ */
+public class UsermgtHibernateMappingFiles extends HibernateMappingFiles {
+
+    public UsermgtHibernateMappingFiles() { 
+       super(new String[] {
+          "hbm/Group.hbm.xml", "hbm/User.hbm.xml"     
+       });
+    }
+    
+    public UsermgtHibernateMappingFiles(String[] aFiles) { 
+        this(); 
+        Collections.addAll(this, aFiles);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/AuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/AuthorizationRule.hbm.xml
new file mode 100644 (file)
index 0000000..33f5d94
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        
+        <class name="org.wamblee.security.authorization.AuthorizationRule" 
+               table="AUTHORIZATION_RULES" 
+               select-before-update="true"
+               lazy="false">
+            <id name="primaryKey" column="ID" type="long">
+                <generator class="native"/>
+            </id>
+            <discriminator column="TYPE" type="string"/>
+            <version name="persistedVersion" column="VERSION"/>
+            
+            <subclass name="org.wamblee.security.authorization.UrlAuthorizationRule"
+                discriminator-value="ISINGROUP"
+                lazy="false">
+                <property name="authorizationResultString" column="RESULT"/>
+                <property name="resourceClassName" column="RESOURCE_CLASSNAME"/>
+                <many-to-one name="userCondition" 
+                             class="org.wamblee.security.authorization.UserCondition"
+                             column="USERCONDITION_ID"
+                             cascade="all"
+                             lazy="false"/>
+                <many-to-one name="pathCondition" 
+                    class="org.wamblee.security.authorization.PathCondition"
+                    column="PATHCONDITION_ID"
+                    cascade="all"
+                    lazy="false"/>
+                <many-to-one name="operationCondition" 
+                    class="org.wamblee.security.authorization.OperationCondition"
+                    column="OPERATIONCONDITION_ID"
+                    cascade="all"
+                    lazy="false"/> 
+            </subclass>
+            
+        </class>
+        
+        
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/AuthorizationService.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/AuthorizationService.hbm.xml
new file mode 100644 (file)
index 0000000..f8e036c
--- /dev/null
@@ -0,0 +1,37 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        
+        <class name="org.wamblee.security.authorization.AuthorizationService" table="AUTHORIZATION_SERVICE" 
+               select-before-update="true">
+            <id name="primaryKey" column="ID" type="long">
+                <generator class="native"/>
+            </id>
+            <discriminator column="TYPE" type="string"/>
+            <version name="persistedVersion" column="VERSION"/>
+            
+            <subclass name="org.wamblee.security.authorization.DefaultAuthorizationService"
+                discriminator-value="DEFAULT">
+                
+                <property name="name" column="NAME"/>
+               
+                <list name="mappedRules" table="AUTHORIZATION_SERVICE_RULES" lazy="false" cascade="all-delete-orphan">
+                    <key column="ID"/>
+                    <index column="POSITION"/>
+                    <many-to-many class="org.wamblee.security.authorization.AuthorizationRule"
+                       column="RULE_ID"/>
+                </list>
+            </subclass>
+            
+        </class>
+        
+        <query name="findAuthorizationServiceByName">
+            select service
+            from org.wamblee.security.authorization.AuthorizationService service
+            where service.name = :name 
+        </query>
+        
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/Group.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/Group.hbm.xml
new file mode 100644 (file)
index 0000000..41e5e6b
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+<hibernate-mapping>
+    
+    <class name="org.wamblee.usermgt.Group" table="GROUPS" select-before-update="true">
+        <id name="primaryKey" column="ID" type="long">
+            <generator class="native"/>
+        </id>
+        <version name="persistedVersion" column="VERSION"/>
+        <property name="name" column="NAME" unique="true"/>
+    </class>
+    
+    <query name="findGroupByName">
+        from org.wamblee.usermgt.Group grp where grp.name = :name
+    </query>
+    
+    <query name="countGroups">
+        select count(*)
+        from org.wamblee.usermgt.Group group 
+    </query>
+    
+</hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/OperationCondition.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/OperationCondition.hbm.xml
new file mode 100644 (file)
index 0000000..5ab4b0d
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        
+        <class name="org.wamblee.security.authorization.OperationCondition" table="OPERATION_CONDITIONS" 
+               select-before-update="true"
+               lazy="false">
+            <id name="primaryKey" column="ID" type="long">
+                <generator class="native"/>
+            </id>
+            <discriminator column="TYPE" type="string"/>
+            <version name="persistedVersion" column="VERSION"/>
+            
+            <subclass name="org.wamblee.security.authorization.IsaOperationCondition"
+                discriminator-value="ISA"
+                lazy="false">
+                <property name="operationString" column="OPERATION"/>
+            </subclass>
+            
+        </class>
+        
+        
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/OperationCondition.hbm.xmlxx b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/OperationCondition.hbm.xmlxx
new file mode 100644 (file)
index 0000000..250030e
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        
+        <class name="org.wamblee.security.authorization.PathCondition" table="PATH_CONDITIONS" 
+               select-before-update="true"
+               lazy="false">
+            <id name="primaryKey" column="ID" type="long">
+                <generator class="native"/>
+            </id>
+            <discriminator column="TYPE" type="string"/>
+            <version name="persistedVersion" column="VERSION"/>
+            
+            <subclass name="org.wamblee.security.authorization.StartsWithPathCondition"
+                discriminator-value="STARTS_WITH"
+                lazy="false">
+                <property name="path" column="PATH"/>
+            </subclass>
+            
+        </class>
+        
+        
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PageAuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PageAuthorizationRule.hbm.xml
new file mode 100644 (file)
index 0000000..332e5d8
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        <subclass name="org.wamblee.photos.authorizationrules.PageAuthorizationRule"
+            extends="org.wamblee.security.authorization.UrlAuthorizationRule"
+            discriminator-value="PAGE"
+            lazy="false"/>
+      
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PathCondition.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PathCondition.hbm.xml
new file mode 100644 (file)
index 0000000..c43c0a8
--- /dev/null
@@ -0,0 +1,32 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        
+        <class name="org.wamblee.security.authorization.PathCondition" table="PATH_CONDITIONS" 
+               select-before-update="true"
+               lazy="false">
+            <id name="primaryKey" column="ID" type="long">
+                <generator class="native"/>
+            </id>
+            <discriminator column="TYPE" type="string"/>
+            <version name="persistedVersion" column="VERSION"/>
+            
+            <subclass name="org.wamblee.security.authorization.RegexpPathCondition"
+                discriminator-value="REGEXP"
+                lazy="false">
+                <property name="pattern" column="PATTERN"/>
+                
+                <subclass name="org.wamblee.security.authorization.StartsWithPathCondition"
+                    discriminator-value="STARTS_WITH"
+                    lazy="false">
+                </subclass>
+                
+            </subclass>
+            
+        </class>
+        
+        
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PhotoAuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/PhotoAuthorizationRule.hbm.xml
new file mode 100644 (file)
index 0000000..fc00dda
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        <subclass name="org.wamblee.photos.authorizationrules.PhotoAuthorizationRule"
+            extends="org.wamblee.security.authorization.AuthorizationRule"
+            discriminator-value="PHOTOS"
+            lazy="false"/>
+      
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/TestAuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/TestAuthorizationRule.hbm.xml
new file mode 100644 (file)
index 0000000..7f796f5
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        <subclass name="org.wamblee.security.authorization.TestAuthorizationRule"
+            extends="org.wamblee.security.authorization.UrlAuthorizationRule"
+            discriminator-value="TEST"
+            lazy="false"/>
+      
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/User.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/User.hbm.xml
new file mode 100644 (file)
index 0000000..eefbfa2
--- /dev/null
@@ -0,0 +1,38 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+<hibernate-mapping>
+    
+    <class name="org.wamblee.usermgt.User" table="USERS" select-before-update="true">
+        <id name="primaryKey" column="ID" type="long">
+            <generator class="native"/>
+        </id>
+        <version name="persistedVersion" column="VERSION"/>
+        <property name="name" column="NAME" unique="true"/>
+        <property name="passwordString" column="PASSWORD"/>
+        <set name="groupSet" table="USER_GROUPS" lazy="false"> 
+            <key column="USER_ID"/>
+            <many-to-many class="org.wamblee.usermgt.Group" column="GROUP_ID"/>
+        </set>
+    </class>
+    
+    <query name="findUserByName">
+        from org.wamblee.usermgt.User user where user.name = :name
+    </query>
+    
+    <query name="findUserByGroupName">
+      select user
+          from org.wamblee.usermgt.User user
+            join user.groupSet grp
+            where grp.name = :name 
+    </query>
+    
+    <query name="countUsers">
+        select count(*)
+        from org.wamblee.usermgt.User user 
+    </query>
+    
+    
+</hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/UserCondition.hbm.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/UserCondition.hbm.xml
new file mode 100644 (file)
index 0000000..fc83423
--- /dev/null
@@ -0,0 +1,31 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+    
+    <hibernate-mapping>
+        
+        <class name="org.wamblee.security.authorization.UserCondition" table="USER_CONDITIONS" 
+               select-before-update="true"
+               lazy="false">
+            <id name="primaryKey" column="ID" type="long">
+                <generator class="native"/>
+            </id>
+            <discriminator column="TYPE" type="string"/>
+            <version name="persistedVersion" column="VERSION"/>
+            
+            <subclass name="org.wamblee.security.authorization.GroupUserCondition"
+                discriminator-value="URL"
+                lazy="false">
+                <property name="group" column="GROUPNAME"/>
+            </subclass>
+            
+            <subclass name="org.wamblee.security.authorization.AnyUserCondition"
+                discriminator-value="ANY"
+                lazy="false">
+            </subclass>
+            
+        </class>
+        
+        
+    </hibernate-mapping>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/ehcache.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/ehcache.xml
new file mode 100644 (file)
index 0000000..ee79950
--- /dev/null
@@ -0,0 +1,75 @@
+<ehcache>
+
+    <!-- Sets the path to the directory where cache .data files are created.
+
+         If the path is a Java System Property it is replaced by
+         its value in the running VM.
+
+         The following properties are translated:
+         user.home - User's home directory
+         user.dir - User's current working directory
+         java.io.tmpdir - Default temp file path -->
+    <diskStore path="java.io.tmpdir"/>
+
+
+    <!--Default Cache configuration. These will applied to caches programmatically created through
+        the CacheManager.
+
+        The following attributes are required:
+
+        maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
+        eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
+                                         element is never expired.
+        overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
+                                         has reached the maxInMemory limit.
+
+        The following attributes are optional:
+        timeToIdleSeconds              - Sets the time to idle for an element before it expires.
+                                         i.e. The maximum amount of time between accesses before an element expires
+                                         Is only used if the element is not eternal.
+                                         Optional attribute. A value of 0 means that an Element can idle for infinity.
+                                         The default value is 0.
+        timeToLiveSeconds              - Sets the time to live for an element before it expires.
+                                         i.e. The maximum time between creation time and when an element expires.
+                                         Is only used if the element is not eternal.
+                                         Optional attribute. A value of 0 means that and Element can live for infinity.
+                                         The default value is 0.
+        diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
+                                         The default value is false.
+        diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
+                                         is 120 seconds.
+        -->
+
+    <defaultCache
+        maxElementsInMemory="10000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="120"
+        timeToLiveSeconds="120"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+        />
+        
+    <cache
+        name="users"
+        maxElementsInMemory="10000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="120"
+        timeToLiveSeconds="120"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+    />
+    
+    <cache
+        name="photos"
+        maxElementsInMemory="1000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="120"
+        timeToLiveSeconds="120"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+    />
+    
+</ehcache>
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/hibernate.properties b/tags/wamblee-utils-0.2.1/security/src/main/resources/hbm/hibernate.properties
new file mode 100644 (file)
index 0000000..42491b2
--- /dev/null
@@ -0,0 +1,20 @@
+
+###################################################################################
+# dialect
+###################################################################################
+hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
+
+###################################################################################
+# debugging settings: Log4j configuration can provide more detail. 
+###################################################################################
+hibernate.show_sql=false
+
+###################################################################################
+# hibernate cache provider
+###################################################################################
+hibernate.cache.provider=org.hibernate.cache.EhCacheProvider
+
+###################################################################################
+# query cache
+###################################################################################
+hibernate.cache.use_query_cache=true
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/properties/org.wamblee.security.ehcache.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/properties/org.wamblee.security.ehcache.xml
new file mode 100644 (file)
index 0000000..ee79950
--- /dev/null
@@ -0,0 +1,75 @@
+<ehcache>
+
+    <!-- Sets the path to the directory where cache .data files are created.
+
+         If the path is a Java System Property it is replaced by
+         its value in the running VM.
+
+         The following properties are translated:
+         user.home - User's home directory
+         user.dir - User's current working directory
+         java.io.tmpdir - Default temp file path -->
+    <diskStore path="java.io.tmpdir"/>
+
+
+    <!--Default Cache configuration. These will applied to caches programmatically created through
+        the CacheManager.
+
+        The following attributes are required:
+
+        maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
+        eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
+                                         element is never expired.
+        overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
+                                         has reached the maxInMemory limit.
+
+        The following attributes are optional:
+        timeToIdleSeconds              - Sets the time to idle for an element before it expires.
+                                         i.e. The maximum amount of time between accesses before an element expires
+                                         Is only used if the element is not eternal.
+                                         Optional attribute. A value of 0 means that an Element can idle for infinity.
+                                         The default value is 0.
+        timeToLiveSeconds              - Sets the time to live for an element before it expires.
+                                         i.e. The maximum time between creation time and when an element expires.
+                                         Is only used if the element is not eternal.
+                                         Optional attribute. A value of 0 means that and Element can live for infinity.
+                                         The default value is 0.
+        diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
+                                         The default value is false.
+        diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
+                                         is 120 seconds.
+        -->
+
+    <defaultCache
+        maxElementsInMemory="10000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="120"
+        timeToLiveSeconds="120"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+        />
+        
+    <cache
+        name="users"
+        maxElementsInMemory="10000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="120"
+        timeToLiveSeconds="120"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+    />
+    
+    <cache
+        name="photos"
+        maxElementsInMemory="1000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="120"
+        timeToLiveSeconds="120"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+    />
+    
+</ehcache>
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.authorization.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.authorization.xml
new file mode 100644 (file)
index 0000000..29f2ff1
--- /dev/null
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+
+<beans>
+    
+    <bean id="org.wamblee.security.authorization.OperationRegistry"
+        class="org.wamblee.security.authorization.DefaultOperationRegistry">
+        <constructor-arg>
+            <list>
+                <bean class="org.wamblee.security.authorization.AllOperation"/>
+                <bean class="org.wamblee.security.authorization.CreateOperation"/>
+                <bean class="org.wamblee.security.authorization.DeleteOperation"/>
+                <bean class="org.wamblee.security.authorization.ReadOperation"/>
+                <bean class="org.wamblee.security.authorization.WriteOperation"/>                
+            </list>
+        </constructor-arg>
+    </bean>
+    
+    <bean id="org.wamblee.security.authorization.AuthorizationService"
+        class="org.wamblee.security.authorization.hibernate.PersistentAuthorizationService">
+        <constructor-arg><value>DEFAULT</value></constructor-arg>
+        <constructor-arg><ref bean="org.springframework.orm.hibernate3.HibernateTemplate"/></constructor-arg>
+        <constructor-arg><ref bean="org.wamblee.usermgt.UserAccessor"/></constructor-arg>
+        <constructor-arg><value type="long">10000</value></constructor-arg>
+    </bean>
+    
+    <!-- any user -->
+    <bean id="anyUserCondition" class="org.wamblee.security.authorization.AnyUserCondition">
+    </bean>
+    
+    <!-- administrators -->
+    <bean id="adminUserCondition" class="org.wamblee.security.authorization.GroupUserCondition">
+        <constructor-arg><value>administrators</value></constructor-arg>
+    </bean>
+   
+</beans> 
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.usermgt-repositories.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.usermgt-repositories.xml
new file mode 100644 (file)
index 0000000..c7ad63c
--- /dev/null
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+ <beans> 
+    
+     <bean id="cacheConfig" class="org.wamblee.io.ClassPathResource">
+         <constructor-arg><value>properties/org.wamblee.security.ehcache.xml</value></constructor-arg>
+     </bean>
+     
+     <bean id="userCache" class="org.wamblee.cache.EhCache">
+         <constructor-arg><ref local="cacheConfig"/></constructor-arg>
+         <constructor-arg><value>users</value></constructor-arg>
+     </bean> 
+     
+    
+    <bean id="passwordValidator" 
+         class="org.wamblee.usermgt.RegexpNameValidator">
+             <constructor-arg><value>.{5,}</value></constructor-arg>
+             <constructor-arg><value>INVALID_PASSWORD</value></constructor-arg>
+             <constructor-arg><value>Password must have at least 5 characters</value></constructor-arg>
+    </bean>
+    
+     <bean id="passwordDigester"
+         class="org.wamblee.security.encryption.Md5HexMessageDigester">
+     </bean>
+    
+    <bean id="org.wamblee.usermgt.UserSet"
+        class="org.wamblee.usermgt.hibernate.HibernateUserSet">
+        <constructor-arg><ref local="userCache"/></constructor-arg>
+        <constructor-arg><ref local="passwordValidator"/></constructor-arg>
+        <constructor-arg><ref local="passwordDigester"/></constructor-arg>
+        
+        <property name="sessionFactory"><ref bean="sessionFactory"/></property>
+        
+    </bean>
+    
+    <bean id="org.wamblee.usermgt.GroupSet"
+        class="org.wamblee.usermgt.hibernate.HibernateGroupSet">
+        
+        <property name="sessionFactory"><ref bean="sessionFactory"/></property>
+    </bean> 
+     
+ </beans>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.usermgt.xml b/tags/wamblee-utils-0.2.1/security/src/main/resources/spring/org.wamblee.security.usermgt.xml
new file mode 100644 (file)
index 0000000..443355f
--- /dev/null
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+ <beans> 
+    
+    <bean id="org.wamblee.usermgt.UserAdministration-target"
+        class="org.wamblee.usermgt.UserAdministrationImpl">
+        
+        <constructor-arg>
+           <ref bean="org.wamblee.usermgt.UserSet"/>
+        </constructor-arg>
+        
+        <constructor-arg>
+            <ref bean="org.wamblee.usermgt.GroupSet"/>
+        </constructor-arg>
+        
+        <constructor-arg>
+            <bean class="org.wamblee.usermgt.RegexpNameValidator">
+                <constructor-arg><value>[a-zA-Z]+[a-zA-Z0-9]*</value></constructor-arg>
+                <constructor-arg><value>INVALID_USERNAME</value></constructor-arg>
+                <constructor-arg><value></value></constructor-arg>
+            </bean>
+        </constructor-arg>
+        
+        <constructor-arg>
+            <bean class="org.wamblee.usermgt.RegexpNameValidator">
+                <constructor-arg><value>[a-zA-Z]+[a-zA-Z0-9]*</value></constructor-arg>
+                <constructor-arg><value>INVALID_GROUPNAME</value></constructor-arg>
+                <constructor-arg><value></value></constructor-arg>
+            </bean>
+        </constructor-arg>
+      
+    </bean>
+    
+    <bean id="usermanagement-lock" class="org.wamblee.concurrency.JvmLock"/>
+    
+     <bean id="usermanagement-lock-advice" class="org.wamblee.concurrency.spring.LockAdvice">
+         <constructor-arg><ref bean="usermanagement-lock"/></constructor-arg>
+     </bean>
+     
+     <bean id="org.wamblee.usermgt.UserAdministration" 
+         class="org.springframework.aop.framework.ProxyFactoryBean">
+         <property name="proxyInterfaces"><value>org.wamblee.usermgt.UserAdministration</value></property>
+         <property name="interceptorNames"><value>usermanagement-lock-advice</value></property>
+         <property name="target"><ref bean="org.wamblee.usermgt.UserAdministration-target"/></property>
+     </bean>
+     
+ </beans>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java
new file mode 100644 (file)
index 0000000..151dbd7
--- /dev/null
@@ -0,0 +1,177 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import static org.wamblee.security.authorization.AuthorizationResult.DENIED;
+import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
+import junit.framework.TestCase;
+
+import org.wamblee.usermgt.UserAccessor;
+
+/**
+ * Tests the authorization service. 
+ *
+ * @author Erik Brakkee
+ */
+public class AuthorizationServiceTest extends TestCase {
+    
+    private AuthorizationRule _rule1; 
+    private AuthorizationRule _rule2;  
+    private AuthorizationRule _rule3; 
+    private AuthorizationService _service; 
+    
+    protected AuthorizationService getService() { 
+        return _service; 
+    }
+    
+    /* (non-Javadoc)
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        
+        _rule1 = createRule(GRANTED, "users", "/oni/", AllOperation.class); 
+        _rule2 = createRule(DENIED, "users", "/abc/", ReadOperation.class); 
+        _rule3 = createRule(GRANTED, "users", "/abc/", AllOperation.class);
+        
+        _service = createService(); 
+        _service.appendRule(_rule1); 
+        _service.appendRule(_rule2);
+        _service.appendRule(_rule3);
+    }
+    
+    protected void resetTestRules() { 
+        ((TestAuthorizationRule)_rule1).reset(); 
+        ((TestAuthorizationRule)_rule2).reset(); 
+        ((TestAuthorizationRule)_rule3).reset(); 
+    }
+    
+    protected UserAccessor createUserAccessor() { 
+        return new TestUserAccessor(); 
+    }
+
+    /**
+     * Creates an authorization service with some rules for testing. . 
+     * @return Authorization service. 
+     */
+    protected AuthorizationService createService() {
+        DefaultAuthorizationService service = new DefaultAuthorizationService() ;
+        service.setUserAccessor(createUserAccessor());
+        return service;
+    }
+    
+    protected AuthorizationRule createRule(AuthorizationResult aResult, String aGroup, String aPath, Class<? extends Operation> aOperation) { 
+        return new TestAuthorizationRule(aResult, aGroup, aPath, aOperation);
+    }
+    
+    protected void checkMatchCount(int aCount, AuthorizationRule aRule) { 
+        assertEquals( aCount,  ((TestAuthorizationRule)aRule).getMatchCount()); 
+    }
+    
+    protected Object createResource(String aPath) { 
+        return new TestResource(aPath);
+    }
+    
+    protected void checkRuleCount(int aCount) { 
+        // Empty
+    }
+    
+    /**
+     * Several checks to verify the outcome of matching against the first rule. 
+     *
+     */
+    public void testFirstRuleGrants() { 
+        assertTrue( _service.isAllowed(createResource("/oni/xyz.jpg"), new ReadOperation())); 
+        checkMatchCount(1, _rule1);
+        assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new WriteOperation())); 
+        checkMatchCount(2, _rule1);
+        assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new DeleteOperation())); 
+        checkMatchCount(3, _rule1);
+        assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new CreateOperation())); 
+        checkMatchCount(4, _rule1);
+        checkMatchCount(0, _rule2);
+        checkMatchCount(0, _rule3);
+    }
+    
+    /**
+     * Verify that a match with the second rule leads to a denial of authorization. 
+     *
+     */
+    public void testSecondRuleDenies() {
+        assertFalse(_service.isAllowed(createResource("/abc/xyz.jpg"), new ReadOperation())); 
+        checkMatchCount(0, _rule1);
+        checkMatchCount(1, _rule2);
+        checkMatchCount(0, _rule3);
+    }
+    
+    /**
+     * Verifies that the third rule is used when appropriate and that it grants access. 
+     *
+     */
+    public void testThirdRuleGrants() { 
+        assertTrue(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation())); 
+        checkMatchCount(0, _rule1); 
+        checkMatchCount(0, _rule2);
+        checkMatchCount(1, _rule3); 
+    }
+    
+    /**
+     * Removes a rule and checks it is removed. 
+     *
+     */
+    public void testRemoveRule() { 
+        checkRuleCount(3);
+        assertTrue(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation())); 
+        _service.removeRule(2); 
+        assertFalse(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation()));
+        checkRuleCount(2);
+    }
+    
+    /**
+     * Inserts a rule and checks it is inserted. 
+     *
+     */
+    public void testInsertRule() {
+        checkRuleCount(3);
+        assertFalse(_service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));     
+        _service.appendRule(createRule(GRANTED, "users", "/janse/", WriteOperation.class));
+        assertTrue(_service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation()));
+        checkRuleCount(4);
+            
+    }
+   
+    /**
+     * Gets the rules. Verifies that all rules are obtained. 
+     *
+     */
+    public void testGetRules() { 
+        AuthorizationRule[] rules = _service.getRules();
+        assertEquals(3, rules.length); 
+    }
+    
+    /**
+     * Verifies that when no rules match, access is denied. 
+     *
+     */
+    public void testNoRulesSupportResource() { 
+        assertFalse(_service.isAllowed(createResource("/xyxyxyxy"), new ReadOperation()));
+        checkMatchCount(0, _rule1); 
+        checkMatchCount(0, _rule2);
+        checkMatchCount(0, _rule3); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java
new file mode 100644 (file)
index 0000000..3dcfe2d
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import junit.framework.TestCase;
+
+/**
+ * Test of the operation registry. 
+ *
+ * @author Erik Brakkee
+ */
+public class DefaultOperationRegistryTest extends TestCase {
+    
+    private OperationRegistry _registry; 
+    
+    /* (non-Javadoc)
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        
+        _registry = new DefaultOperationRegistry(new Operation[] {
+                new AllOperation(), 
+                new ReadOperation(), 
+                new WriteOperation(), 
+                new DeleteOperation(), 
+                new CreateOperation()
+        });     
+    }
+    
+    /**
+     * Tests encoding and decoding of no operations. 
+     *
+     */
+    public void testEncodeDecodeNooperations() { 
+        assertEquals("", _registry.encode(new Operation[0]));
+        assertEquals(0, _registry.decode(Object.class, "").length);
+    }
+    
+    /**
+     * Verifies that encoding of operations into a string works. 
+     *
+     */
+    public void testEncode() { 
+        assertEquals("read,write", _registry.encode(new Operation[] { new ReadOperation(), new WriteOperation() })); 
+    }
+    
+    /**
+     * Verifies that decoding of operation from a string works. 
+     *
+     */
+    public void testDecode() { 
+        Operation[] operations = _registry.decode(Object.class, "read,write");
+        assertTrue( operations[0] instanceof ReadOperation); 
+        assertTrue( operations[1] instanceof WriteOperation); 
+    }
+    
+    /**
+     * Verifies that an IllegalArgumentException occurs when attempting to decode
+     * an operation that is not known. 
+     *
+     */
+    public void testDecodeUnknownOperation() { 
+        try {  
+            _registry.decode(Object.class, "bla"); 
+            fail(); 
+        } catch (IllegalArgumentException e) { 
+            // ok
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java
new file mode 100644 (file)
index 0000000..cf83b28
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import junit.framework.TestCase;
+
+/**
+ * Test for regular expression matching. 
+ *
+ * @author Erik Brakkee
+ */
+public class RegexpPathConditionTest extends TestCase {
+
+    /**
+     * Various tests. 
+     *
+     */
+    public void testMatch() { 
+       PathCondition cond = new RegexpPathCondition("abc"); 
+       assertTrue(cond.matches("abc"));
+       assertFalse(cond.matches("xabcx"));
+       cond = new RegexpPathCondition("/[a-z]*/.*"); 
+       assertTrue(cond.matches("/hallo/xyz")); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java
new file mode 100644 (file)
index 0000000..2e64098
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for StartsWithPathCondition. 
+ *
+ * @author Erik Brakkee
+ */
+public class StartsWithPathConditionTest extends TestCase {
+
+    /**
+     * Various tests. 
+     */
+    public void testMatches() {
+        PathCondition cond = new StartsWithPathCondition("/hallo");
+        assertTrue(cond.matches("/hallo"));
+        assertTrue(cond.matches("/hallox"));
+        assertTrue(cond.matches("/hallo/abc"));
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java
new file mode 100644 (file)
index 0000000..93141fd
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import static org.wamblee.security.authorization.AuthorizationResult.DENIED;
+import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
+
+import org.wamblee.usermgt.User;
+
+/**
+ * Test authorization rule that also counts the number of times the rule matches. 
+ *
+ * @author Erik Brakkee
+ */
+public class TestAuthorizationRule extends UrlAuthorizationRule {
+    
+    /**
+     * Counts the number of matches. 
+     */
+    private int _matches = 0; 
+
+    public TestAuthorizationRule( AuthorizationResult aResult, String aGroup,
+            String aPath, Class<? extends Operation> aOperation) {
+       super(aResult, new GroupUserCondition(aGroup), 
+               new StartsWithPathCondition(aPath), TestResource.class, new IsaOperationCondition(aOperation));
+    }
+    
+    protected TestAuthorizationRule() { 
+        super();
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.UrlAuthorizationRule#getPath(java.lang.Object)
+     */
+    @Override
+    protected String getResourcePath(Object aResource) {
+        return ((TestResource)aResource).getPath();
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.security.authorization.UrlAuthorizationRule#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation, org.wamblee.usermgt.UserAccessor)
+     */
+    @Override
+    public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) {
+        
+        AuthorizationResult result = super.isAllowed(aResource, anOperation, aUser);
+        if ( result.equals(GRANTED) || result.equals(DENIED)) { 
+            _matches++; 
+        }
+        return result; 
+    }
+    
+    public int getMatchCount() { 
+        return _matches; 
+    }
+    
+    public void reset() { 
+        _matches = 0; 
+    }
+   
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestResource.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestResource.java
new file mode 100644 (file)
index 0000000..a0edd89
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+/**
+ * A test resource for authorization. 
+ *
+ * @author Erik Brakkee
+ */
+public class TestResource {
+
+    private String _path; 
+    
+    public TestResource(String aPath) { 
+        _path = aPath;     
+    }
+    
+    public String getPath() { 
+        return _path; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java
new file mode 100644 (file)
index 0000000..02e0902
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import junit.framework.TestCase;
+
+import org.wamblee.security.encryption.Md5HexMessageDigester;
+import org.wamblee.usermgt.Group;
+import org.wamblee.usermgt.InMemoryGroupSet;
+import org.wamblee.usermgt.InMemoryUserSet;
+import org.wamblee.usermgt.RegexpNameValidator;
+import org.wamblee.usermgt.User;
+import org.wamblee.usermgt.UserAccessor;
+import org.wamblee.usermgt.UserAdministration;
+import org.wamblee.usermgt.UserAdministrationImpl;
+import org.wamblee.usermgt.UserMgtException;
+import org.wamblee.usermgt.UserMgtException.Reason;
+
+/**
+ * User access that always returns a user that belongs to
+ * a fixed group. 
+ *
+ * @author Erik Brakkee
+ */
+public class TestUserAccessor implements UserAccessor {
+    
+    private static final String USER = "erik"; 
+    private static final String PASSWORD = "abc123";
+    private static final String GROUP = "users";
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAccessor#getCurrentUser()
+     */
+    public User getCurrentUser() {
+        UserAdministration admin = new UserAdministrationImpl(
+                new InMemoryUserSet(    new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"),
+                        new Md5HexMessageDigester()), new InMemoryGroupSet(),
+                new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, Reason.INVALID_USERNAME, "Invalid user"), 
+                new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, Reason.INVALID_GROUPNAME, "Invalid group")
+        );
+        try {
+            Group group = admin.createGroup(GROUP);
+            return admin.createUser(USER, PASSWORD, group);
+        } catch (UserMgtException e) {
+            TestCase.fail(e.getMessage());
+            throw new RuntimeException(e);
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java
new file mode 100644 (file)
index 0000000..4e66ed8
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright 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.wamblee.security.authorization;
+
+import static org.wamblee.security.authorization.AuthorizationResult.GRANTED;
+import static org.wamblee.security.authorization.AuthorizationResult.UNDECIDED;
+import static org.wamblee.security.authorization.AuthorizationResult.UNSUPPORTED_RESOURCE;
+import junit.framework.TestCase;
+
+import org.wamblee.usermgt.User;
+
+
+/**
+ * Tests for the {@link org.wamblee.security.authorization.UrlAuthorizationRule}. 
+ *
+ * @author Erik Brakkee
+ */
+public class UrlAuthorizationRuleTest extends TestCase {
+
+    /**
+     * Constructs the rule with a result of UNDECIDED. Verifies that an IllegalArgumentException 
+     * is thrown. 
+     *
+     */
+    public void testConstructWithUndecidedResult() { 
+        try { 
+            new TestAuthorizationRule(UNDECIDED, "users", "/path", ReadOperation.class);
+            fail();
+        } catch (IllegalArgumentException e) { 
+            // ok 
+        }
+    }
+    
+    /**
+     * Constructs the rule with a result of UNSUPPORTED_RESOURCE. Verifies that an IllegalArgumentException 
+     * is thrown. 
+     *
+     */
+    public void testConstructWithUnsupportedResult() { 
+        try { 
+            new TestAuthorizationRule(UNSUPPORTED_RESOURCE, "users", "/path", ReadOperation.class);
+            fail();
+        } catch (IllegalArgumentException e) { 
+            // ok 
+        }
+    }
+    
+    /**
+     * Constructs the authorization rule and applies it to an unsupported object type. 
+     * Verifies that the result is UNSUPPORTED_RESOURCE. 
+     *
+     */
+    public void testUnsupportedObject() { 
+        AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users", "/path", ReadOperation.class);
+        assertEquals(UNSUPPORTED_RESOURCE, rule.isAllowed("hello", new ReadOperation(), new TestUserAccessor().getCurrentUser()));
+    }
+    
+    public void testMatchingScenarios() { 
+        AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users", "/path/", ReadOperation.class);
+        User user = new TestUserAccessor().getCurrentUser();
+        
+        // everything matches
+        assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/a"), new ReadOperation(), user));
+        assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/"), new ReadOperation(), user));
+        
+        // path does not match. 
+        assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path"), new ReadOperation(), user));
+        
+        // operation does not match. 
+        assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path/"), new WriteOperation(), user));
+        
+        // group does not match. 
+        AuthorizationRule rule2 = new TestAuthorizationRule(GRANTED, "users2", "/path/", ReadOperation.class);
+        assertEquals(UNDECIDED, rule2.isAllowed(new TestResource("/path/a"), new ReadOperation(), user));
+    }
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java
new file mode 100644 (file)
index 0000000..f55fc29
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * Copyright 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.wamblee.security.authorization.hibernate;
+
+import java.sql.SQLException;
+
+import org.apache.log4j.Logger;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.dialect.MySQL5Dialect;
+import org.hibernate.dialect.MySQL5InnoDBDialect;
+import org.hibernate.tool.hbm2ddl.SchemaExport;
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.wamblee.general.BeanKernel;
+import org.wamblee.security.authorization.AuthorizationService;
+import org.wamblee.security.authorization.AuthorizationServiceTest;
+import org.wamblee.security.authorization.TestUserAccessor;
+import org.wamblee.system.adapters.ClassConfiguration;
+import org.wamblee.system.adapters.ClassConfigurationTest;
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.components.DatabaseComponentFactory;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.component.DatabaseTesterComponent;
+import org.wamblee.system.spring.component.DatasourceComponent;
+import org.wamblee.usermgt.UserAccessor;
+import org.wamblee.usermgt.hibernate.AuthorizationComponent;
+import org.wamblee.usermgt.hibernate.HibernateUserAdministrationTest;
+import org.wamblee.usermgt.hibernate.UserAdministrationComponent;
+
+/**
+ * Unit test for the persistent authorization service.
+ * 
+ * @author Erik Brakkee
+ */
+public class PersistentAuthorizationServiceTest extends
+        AuthorizationServiceTest {
+
+    private static final Logger LOGGER = Logger
+            .getLogger(PersistentAuthorizationServiceTest.class);
+
+    private static final String SERVICE_TABLE = "AUTHORIZATION_SERVICE";
+    private static final String RULES_TABLE = "AUTHORIZATION_RULES";
+    private static final String SERVICE_RULES_TABLE = "AUTHORIZATION_SERVICE_RULES";
+    private static final String OPERATIONCOND_TABLE = "OPERATION_CONDITIONS";
+    private static final String PATHCOND_TABLE = "PATH_CONDITIONS";
+    private static final String USERCOND_TABLE = "USER_CONDITIONS";
+
+    private DefaultContainer _container;
+    private Scope _scope;
+
+    private DatabaseTesterComponent _databaseTester;
+    private UserAccessor _userAccessor;
+    private HibernateTemplate _hibernateTemplate;
+    private AuthorizationService _authorizationService;
+
+    @Override
+    protected void setUp() throws Exception {
+
+        _container = new DefaultContainer("top");
+        DatabaseComponentFactory.addDatabaseConfig(_container);
+        _container.addComponent(new DatasourceComponent("datasource"));
+        ClassConfiguration useraccessorConfig = new ClassConfiguration(
+                TestUserAccessor.class);
+        useraccessorConfig.getObjectConfig().getSetterConfig().initAllSetters();
+        _container.addComponent("userAccessor", useraccessorConfig);
+        _container.addComponent(new AuthorizationComponent("authorization",
+                true));
+
+        ClassConfiguration dbtesterConfig = new ClassConfiguration(
+                DatabaseTesterComponent.class);
+        dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
+        _container.addComponent("databaseTester", dbtesterConfig);
+
+        ObjectConfiguration config = new ObjectConfiguration(
+                PersistentAuthorizationServiceTest.class);
+        config.getSetterConfig().clear().add("setUserAccessor").add(
+                "setDatabaseTester").add("setHibernateTemplate").add(
+                "setAuthorizationService");
+        _container.addComponent("testcase", this, config);
+
+        _scope = _container.start();
+
+        _databaseTester.cleanDatabase();
+
+        super.setUp();
+    }
+
+    public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
+        _databaseTester = aDatabaseTester;
+    }
+
+    public void setUserAccessor(UserAccessor aUserAccessor) {
+        _userAccessor = aUserAccessor;
+    }
+
+    public void setHibernateTemplate(HibernateTemplate aHibernateTemplate) {
+        _hibernateTemplate = aHibernateTemplate;
+    }
+
+    public void setAuthorizationService(
+            AuthorizationService aAuthorizationService) {
+        _authorizationService = aAuthorizationService;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see
+     * org.wamblee.security.authorization.AuthorizationServiceTest#createService
+     * ()
+     */
+    @Override
+    protected AuthorizationService createService() {
+        PersistentAuthorizationService service = new PersistentAuthorizationService(
+                "DEFAULT", _hibernateTemplate, createUserAccessor(), 10000);
+        return service;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see
+     * org.wamblee.security.authorization.AuthorizationServiceTest#checkRuleCount
+     * (int)
+     */
+    @Override
+    protected void checkRuleCount(int aCount) {
+        try {
+            assertEquals(1, _databaseTester.getTableSize(SERVICE_TABLE));
+            assertEquals(aCount, _databaseTester.getTableSize(RULES_TABLE));
+            assertEquals(aCount, _databaseTester
+                    .getTableSize(SERVICE_RULES_TABLE));
+            assertEquals(aCount, _databaseTester.getTableSize(USERCOND_TABLE));
+            assertEquals(aCount, _databaseTester.getTableSize(PATHCOND_TABLE));
+            assertEquals(aCount, _databaseTester
+                    .getTableSize(OPERATIONCOND_TABLE));
+        } catch (SQLException e) {
+            throw new RuntimeException(e);
+        }
+
+    }
+
+    public void testSchemaExport() { 
+        Configuration config = new Configuration();
+        for (String mappingFile: new AuthorizationMappingFiles()) { 
+           config.addResource(mappingFile);
+        }
+        config.setProperty("hibernate.dialect", MySQL5InnoDBDialect.class.getName());
+        SchemaExport exporter = new SchemaExport(config);
+        exporter.setOutputFile("target/mysql5.schema.sql");
+        exporter.create(true,false);
+    }
+
+    public void testPerformance() {
+
+        PersistentAuthorizationService service = (PersistentAuthorizationService) getService();
+
+        int n = 1000;
+        long time = System.currentTimeMillis();
+        for (int i = 0; i < n; i++) {
+            testFirstRuleGrants();
+            resetTestRules();
+            testSecondRuleDenies();
+            resetTestRules();
+            testThirdRuleGrants();
+            resetTestRules();
+            testNoRulesSupportResource();
+        }
+        LOGGER.info("Executed " + 4 * n + " authorization checks in "
+                + (float) (System.currentTimeMillis() - time) / (float) 1000
+                + " seconds.");
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java
new file mode 100644 (file)
index 0000000..6760efe
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright 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.wamblee.security.encryption;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for the message digester. 
+ *
+ * @author Erik Brakkee
+ */
+public class MessageDigesterTest extends TestCase {
+
+    public void testMd5HexEncoding() { 
+        assertEquals("e99a18c428cb38d5f260853678922e03", new Md5HexMessageDigester().hash("abc123"));
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java
new file mode 100644 (file)
index 0000000..2ea1190
--- /dev/null
@@ -0,0 +1,188 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.sql.SQLException;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the inmemory group set. Intended to be subclassed for other
+ * implementations of group set. 
+ */
+public class InMemoryGroupSetTest extends TestCase {
+    
+    protected GroupSet _groups; 
+   
+    /**
+     * This method must be overriden in subclasses. 
+     * @return New group set object. 
+     */
+    protected GroupSet createGroupSet() { 
+        return new InMemoryGroupSet(); 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.test.SpringTestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        _groups = createGroupSet(); 
+        checkGroupCount(0); 
+    }
+    
+    
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aGroup Group to check for existence. 
+     */
+    protected void checkGroupExists(String aGroup) throws SQLException { 
+        // Empty
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aGroup Group to check for non-existence. 
+     */
+    protected void checkGroupNotExists(String aGroup) throws SQLException { 
+        // Empty
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aSize Expected number of groups. 
+     */
+    protected void checkGroupCount(int aSize) throws SQLException { 
+        assertEquals(aSize, _groups.size());
+    }
+    
+    /**
+     * Adds a group and verifies that the group is added using 
+     * find(), list(),  and contains().  
+     *
+     */
+    public void testAdd() throws SQLException { 
+       Group group = new Group("group1"); 
+       assertTrue(  _groups.add(group) );
+       checkGroupExists(group.getName());
+       checkGroupCount(1);
+       Group group2 = _groups.find("group1"); 
+       assertNotNull(group2);
+       assertEquals(group.getName(), group2.getName()); 
+       Set<Group> set = _groups.list(); 
+       assertEquals(1, set.size()); 
+       assertTrue(set.contains(group));
+    }
+    
+    /**
+     * Tries to find a non-existing group. Verifies that null is
+     * returned. 
+     *
+     */
+    public void testFindUnknownGroup() throws SQLException { 
+       Group group1 = new Group("group1"); 
+       Group group2 = new Group("group2");
+       _groups.add(group1); 
+       _groups.add(group2);
+       checkGroupExists(group1.getName()); 
+       checkGroupExists(group2.getName()); 
+    
+       assertNull( _groups.find("group3") );
+       checkGroupNotExists("group3");
+    }
+    
+    /**
+     * Adds duplicate group. Verifies that the existing group is left untouched.  
+     */
+    public void testAddDuplicateGroup() throws SQLException { 
+       Group group1 = new Group("group1"); 
+       _groups.add(group1); 
+       
+       assertEquals(1, _groups.list().size()); 
+       assertTrue(_groups.contains(group1));
+       group1 = new Group("group1");
+       assertFalse(_groups.add(group1));
+       assertEquals(1, _groups.list().size());
+       
+       checkGroupExists(group1.getName()); 
+       checkGroupCount(1); 
+    }
+    
+    /**
+     * Removes a group. Verifies that the group is 
+     * removed and the return value is true. 
+     *
+     */
+    public void testRemoveGroup() throws SQLException { 
+        Group group1 = new Group("group1"); 
+        _groups.add(group1); 
+        assertTrue(_groups.contains(group1));
+        checkGroupCount(1);
+        
+        assertTrue(_groups.remove(group1)); 
+        assertFalse(_groups.contains(group1)); 
+        assertNull(_groups.find(group1.getName()));
+        assertEquals(0, _groups.list().size());
+        checkGroupCount(0);
+    }
+  
+    /**
+     * Removes a non-existing group. Verifies that no groups are
+     * removed an that the return value is true. 
+     *
+     */
+    public void testRemoveNonExistingGroup() throws SQLException { 
+        Group group1 = new Group("group1"); 
+        _groups.add(group1); 
+        checkGroupCount(1);
+        Group nonExistingGroup = new Group("group2"); 
+        nonExistingGroup.setPrimaryKey(new Long(1000));
+        nonExistingGroup.setPersistedVersion(1000);
+        assertFalse(_groups.remove(nonExistingGroup));
+        assertTrue(_groups.contains(group1)); 
+        assertEquals(1, _groups.list().size());
+        checkGroupCount(1); 
+    }
+    
+    /**
+     * Adds a number of groups to the set and verifies that list() 
+     * returns them all. 
+     *
+     */
+    public void testList() throws SQLException { 
+        Group group1 = new Group("group1"); 
+        Group group2 = new Group("group2"); 
+        Group group3 = new Group("group3"); 
+        assertTrue(_groups.add(group1)); 
+        assertTrue(_groups.add(group2)); 
+        assertTrue(_groups.add(group3));
+        
+        checkGroupExists(group1.getName()); 
+        checkGroupExists(group2.getName()); 
+        checkGroupExists(group3.getName()); 
+        
+        Set<Group> set = _groups.list(); 
+        assertTrue(set.contains(group1)); 
+        assertTrue(set.contains(group2)); 
+        assertTrue(set.contains(group3));
+        
+        checkGroupCount(3); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java
new file mode 100644 (file)
index 0000000..8d60d43
--- /dev/null
@@ -0,0 +1,312 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.sql.SQLException;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.wamblee.security.encryption.Md5HexMessageDigester;
+import org.wamblee.usermgt.UserMgtException.Reason;
+
+/**
+ * Tests the inmemory user set. Intended to be subclassed for other
+ * implementations of user set. 
+ */
+public class InMemoryUserSetTest extends TestCase {
+    
+    protected static final String PASSWORD = "abc123";
+    
+    private UserSet _users;
+    private GroupSet _groups;
+    
+    private Group _group; 
+    
+    /**
+     * This method must be overriden in subclasses. 
+     * @return New user set object. 
+     */
+    protected UserSet createUserSet() { 
+        return new InMemoryUserSet(   new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"),
+                new Md5HexMessageDigester()); 
+    }
+    
+    /**
+     * This method must be overriden in subclasses. 
+     * @return New group set object. 
+     */
+    protected GroupSet createGroupSet() { 
+        return new InMemoryGroupSet(); 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.test.SpringTestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        _users = createUserSet();
+        _groups = createGroupSet(); 
+        _group = new Group("group0");
+        _groups.add(_group);
+        checkUserCount(0);
+        
+    }
+    
+    protected UserSet getUsers() { 
+        return _users; 
+    }
+    
+    protected GroupSet getGroups() { 
+        return _groups; 
+    }
+    
+    protected Group createGroup(String aName) { 
+        return new Group(aName);
+    }
+    
+    protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { 
+        return UsermgtTestUtils.createUser(aName, aPassword, aGroup);
+    }
+    
+    protected void addUserToGroup(User aUser, Group aGroup) throws UserMgtException { 
+        aUser.addGroup(aGroup); 
+    }
+    
+    protected void removeUserFromGroup(User aUser, Group aGroup ) throws UserMgtException { 
+        aUser.removeGroup(aGroup); 
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aUser User to check for existence. 
+     */
+    protected void checkUserExists(String aUser) throws SQLException { 
+        // Empty
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aUser User to check for non-existence. 
+     */
+    protected void checkUserNotExists(String aUser) throws SQLException { 
+        // Empty
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aSize Expected number of users. 
+     */
+    protected void checkUserCount(int aSize) throws SQLException { 
+        assertEquals(aSize, _users.size()); 
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aUser User to check for existence. 
+     */
+    protected void checkGroupExists(String aUser) throws SQLException { 
+        // Empty
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aUser User to check for non-existence. 
+     */
+    protected void checkGroupNotExists(String aUser) throws SQLException { 
+        // Empty
+    }
+    
+    /**
+     * Additional check to be implemented by a subclass. 
+     * @param aSize Expected number of users. 
+     */
+    protected void checkGroupCount(int aSize) throws SQLException { 
+        // Empty
+    }
+   
+    
+    /**
+     * Adds a user and verifies that the user is added using 
+     * find(), list(),  and contains().  
+     *
+     */
+    public void testAdd() throws SQLException, UserMgtException { 
+       User user = createUser("user1", PASSWORD, _group); 
+       assertTrue(  _users.add(user) );
+       checkUserExists(user.getName());
+       checkUserCount(1);
+       User user2 = _users.find("user1"); 
+       assertNotNull(user2);
+       assertEquals(user.getName(), user2.getName()); 
+       Set<User> set = _users.list(); 
+       assertEquals(1, set.size()); 
+       assertTrue(set.contains(user));
+    }
+    
+    /**
+     * Tries to find a non-existing user. Verifies that null is
+     * returned. 
+     *
+     */
+    public void testFindUnknownUser() throws SQLException, UserMgtException { 
+       User user1 = createUser("user1", PASSWORD, _group); 
+       User user2 = createUser("user2", PASSWORD, _group);
+       _users.add(user1); 
+       _users.add(user2);
+       checkUserExists(user1.getName()); 
+       checkUserExists(user2.getName()); 
+    
+       assertNull( _users.find("user3") );
+       checkUserNotExists("user3");
+    }
+    
+    /**
+     * Adds duplicate user. Verifies that the existing user is left untouched.  
+     */
+    public void testAddDuplicateUser() throws SQLException, UserMgtException { 
+       User user1 = createUser("user1", PASSWORD, _group); 
+       _users.add(user1); 
+       
+       assertEquals(1, _users.list().size()); 
+       assertTrue(_users.contains(user1)); 
+       user1 = createUser("user1", PASSWORD, _group); 
+       assertFalse(_users.add(user1));
+       assertEquals(1, _users.list().size());
+       
+       checkUserExists(user1.getName()); 
+       checkUserCount(1); 
+    }
+    
+    /**
+     * Removes a user. Verifies that the user is 
+     * removed and the return value is true. 
+     *
+     */
+    public void testRemoveUser() throws SQLException, UserMgtException { 
+        User user1 = createUser("user1", PASSWORD, _group); 
+        _users.add(user1); 
+        assertTrue(_users.contains(user1));
+        checkUserCount(1);
+        
+        assertTrue(_users.remove(user1)); 
+        assertFalse(_users.contains(user1)); 
+        assertNull(_users.find(user1.getName()));
+        assertEquals(0, _users.list().size());
+        checkUserCount(0);
+    }
+  
+    /**
+     * Removes a non-existing user. Verifies that no users are
+     * removed an that the return value is true. 
+     *
+     */
+    public void testRemoveNonExistingUser() throws SQLException, UserMgtException { 
+        User user1 = createUser("user1", PASSWORD, _group); 
+        _users.add(user1); 
+        checkUserCount(1);
+        User nonExistingUser = createUser("user2", PASSWORD, _group);
+        nonExistingUser.setPrimaryKey(new Long(1000));
+        nonExistingUser.setPersistedVersion(10);
+        assertFalse(_users.remove(nonExistingUser));
+        assertTrue(_users.contains(user1)); 
+        assertEquals(1, _users.list().size());
+        checkUserCount(1); 
+    }
+    
+    /**
+     * Adds a number of users to the set and verifies that list() 
+     * returns them all. 
+     *
+     */
+    public void testList() throws SQLException, UserMgtException { 
+        User user1 = createUser("user1", PASSWORD, _group); 
+        User user2 = createUser("user2", PASSWORD, _group); 
+        User user3 = createUser("user3", PASSWORD, _group); 
+        assertTrue(_users.add(user1)); 
+        assertTrue(_users.add(user2)); 
+        assertTrue(_users.add(user3));
+        
+        checkUserExists(user1.getName()); 
+        checkUserExists(user2.getName()); 
+        checkUserExists(user3.getName()); 
+        
+        Set<User> set = _users.list(); 
+        assertTrue(set.contains(user1)); 
+        assertTrue(set.contains(user2)); 
+        assertTrue(set.contains(user3));
+        
+        checkUserCount(3); 
+    }
+    
+    /**
+     * Adds several users to different groups and verifies that 
+     * the correct users are returned when looking for users in 
+     * different groups. 
+     * @throws SQLException
+     */
+    public void testListByGroup() throws SQLException, UserMgtException {
+        Group group1 = new Group("group1"); 
+        Group group2 = new Group("group2");
+        Group group3 = new Group("group3");
+        _groups.add(group1); 
+        _groups.add(group2); 
+        _groups.add(group3);
+        
+        //           user1    user2    user3
+        // group1     y         
+        // group2     y       y           
+        // group3     y       y           y
+        
+        User user1 = createUser("user1", PASSWORD, group1);
+        user1.addGroup(group2); 
+        user1.addGroup(group3);
+        User user2 = createUser("user2", PASSWORD, group2); 
+        user2.addGroup(group3); 
+        User user3 = createUser("user3", PASSWORD, group3);
+        _users.add(user1); 
+        _users.add(user2); 
+        _users.add(user3);
+        
+        checkUserExists(user1.getName());
+        checkUserExists(user2.getName()); 
+        checkUserExists(user3.getName()); 
+        
+        checkGroupExists(group1.getName());
+        checkGroupExists(group2.getName()); 
+        checkGroupExists(group3.getName()); 
+        
+        checkUserCount(3); 
+        checkGroupCount(3+1); // also count the group that was created in the setUp().
+        
+        Set<User> list = _users.list(group1);
+        assertTrue(list.contains(user1)); 
+        assertEquals(1, list.size());
+        
+        list = _users.list(group2); 
+        assertTrue(list.contains(user1));
+        assertTrue(list.contains(user2));
+        assertEquals(2, list.size());
+        
+        list = _users.list(group3); 
+        assertTrue(list.contains(user1));
+        assertTrue(list.contains(user2));
+        assertTrue(list.contains(user3));
+        assertEquals(3, list.size());
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java
new file mode 100644 (file)
index 0000000..055828d
--- /dev/null
@@ -0,0 +1,603 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.apache.log4j.Logger;
+import org.wamblee.security.encryption.Md5HexMessageDigester;
+import org.wamblee.usermgt.UserMgtException.Reason;
+
+/**
+ * Test of user administration implementation.
+ *
+ * @author Erik Brakkee
+ */
+public class UserAdministrationImplTest extends TestCase {
+
+    private static final Logger LOGGER = Logger
+            .getLogger(UserAdministrationImplTest.class);
+
+    private static final String USER1 = "piet";
+
+    private static final String PASS1 = "passpiet";
+
+    private static final String USER2 = "kees";
+
+    private static final String PASS2 = "passkees";
+
+    private static final String GROUP1 = "cyclists";
+
+    private static final String GROUP2 = "runners";
+
+    private UserAdministration _admin;
+
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        _admin = createAdmin();
+    }
+
+    protected UserAdministration createAdmin() {
+        UserSet users = new InMemoryUserSet(   new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"),
+                new Md5HexMessageDigester());
+        GroupSet groups = new InMemoryGroupSet();
+        return new UserAdministrationImpl(users, groups,
+                new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+                        Reason.INVALID_USERNAME, "Invalid user"),
+                new RegexpNameValidator(RegexpNameValidator.ID_PATTERN,
+                        Reason.INVALID_GROUPNAME, "Invalid group"));
+    }
+    
+    protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { 
+        return UsermgtTestUtils.createUser(aName, aPassword, aGroup);
+    }
+
+    /**
+     * Constructs the admin, verify it contains no users and no groups.
+     */
+    public void testConstruct() {
+        assertEquals(0, _admin.getUsers().size());
+        assertEquals(0, _admin.getGroups().size());
+        assertEquals(0, _admin.getUserCount());
+        assertEquals(0, _admin.getGroupCount());
+    }
+
+    /**
+     * Creates a new group. Verifies the group is created correctly and that the
+     * user is added.
+     * 
+     */
+    public void testCreateGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        assertNotNull(group);
+        assertEquals(GROUP1, group.getName());
+
+        Set<Group> groups = _admin.getGroups();
+        assertEquals(1, groups.size());
+        assertEquals(1, _admin.getGroupCount());
+        assertTrue(groups.contains(group));
+    }
+
+    private void createInvalidGroup(String aUsername) {
+        try {
+            _admin.createGroup(aUsername);
+            fail();
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.INVALID_GROUPNAME, e
+                    .getReason());
+            assertEquals(0, _admin.getGroupCount());
+        }
+    }
+
+    /**
+     * Creates a new group with an invalid name. Verifies that the appropriate
+     * exception is thrown.
+     * 
+     * @throws UserMgtException
+     */
+    public void testCreateInvalidGroupName() throws UserMgtException {
+        createInvalidGroup("");
+        createInvalidGroup("0abc"); // should not start with digits
+        createInvalidGroup("a b"); // should not contain spaces
+        createInvalidGroup(" aa");
+        createInvalidGroup("aa ");
+    }
+
+    /**
+     * Creates a new group which conflicts with an existing one. Verifies that
+     * the UserMgtException is thrown and that no group is added.
+     * 
+     */
+    public void testCreateDuplicateGroup() throws UserMgtException {
+        _admin.createGroup(GROUP1);
+        try {
+            _admin.createGroup(GROUP1);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason());
+            assertEquals(1, _admin.getGroupCount());
+            return;
+        }
+        fail();
+    }
+
+    /**
+     * Creates a new user. Verifies the user is created correctly and that the
+     * user is added.
+     * 
+     */
+    public void testCreateUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        assertNotNull(user);
+        assertEquals(USER1, user.getName());
+        user.checkPassword(PASS1);
+
+        Set<User> users = _admin.getUsers();
+        assertEquals(1, users.size());
+        assertEquals(1, _admin.getUserCount());
+        assertTrue(users.contains(user));
+    }
+
+    private void createInvalidUser(String aUsername, Group aGroup) {
+        try {
+            _admin.createUser(aUsername, "pass", aGroup);
+            fail();
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.INVALID_USERNAME, e
+                    .getReason());
+            assertEquals(0, _admin.getUserCount());
+        }
+    }
+
+    /**
+     * Constructs users with invalid names. Verifies that the appropriate
+     * exception is thrown.
+     * 
+     */
+    public void testCreateInvalidUserName() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        createInvalidUser("", group);
+        createInvalidUser("0abc", group); // should not start with digits
+        createInvalidUser("a b", group); // should not contain spaces
+        createInvalidUser(" aa", group);
+        createInvalidUser("aa ", group);
+    }
+
+    /**
+     * Creates a new user which conflicts with an existing one. Verifies that
+     * the UserMgtException is thrown and that no user is added.
+     * 
+     */
+    public void testCreateDuplicateUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        _admin.createUser(USER1, PASS1, group);
+        try {
+            _admin.createUser(USER1, PASS2, group);
+            fail();
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.DUPLICATE_USER, e.getReason());
+            assertEquals(1, _admin.getUserCount());
+        }
+    }
+
+    /**
+     * Gets a known user by name. Verifies the correct user is obtained.
+     * Verifies that null is returned when trying to obtain an unknown user.
+     * 
+     */
+    public void testGetUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        User user2 = _admin.getUser(USER1);
+        assertTrue(user.equals(user2));
+        assertNull(_admin.getUser(USER2));
+    }
+
+    /**
+     * Gets a known group by name. Verifies the correct group is obtained.
+     * Verifies that null is returned when the group is not known.
+     * 
+     */
+    public void testGetGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        Group group2 = _admin.getGroup(GROUP1);
+        assertTrue(group.equals(group2));
+        assertNull(_admin.getGroup(GROUP2));
+    }
+
+    /**
+     * Adds a user to a group. Verifies that the user is added using several API
+     * calls. Verifies that an exception occurs if the user is not already part
+     * of the group.
+     * 
+     */
+    public void testAddUserToGroup() throws UserMgtException {
+
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        Group group2 = _admin.createGroup(GROUP2);
+        assertTrue(user.isInGroup(group));
+        assertFalse(user.isInGroup(group2));
+        _admin.addUserToGroup(user, group2);
+        assertTrue(user.isInGroup(group));
+        assertTrue(user.isInGroup(group2));
+        Set<User> users = _admin.getUsers(group2);
+        assertNotNull(users);
+        assertEquals(1, users.size());
+        assertTrue(users.contains(user));
+
+        try {
+            _admin.addUserToGroup(user, group);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP, e
+                    .getReason());
+            return;
+        }
+        fail();
+    }
+
+    /**
+     * Adds a user to a group where the user does not exist. Verifies that an
+     * exception occurs.
+     * 
+     */
+    public void testAddUserToGroupUnknownUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = createUser(USER1, PASS1, group);
+        try {
+            _admin.addUserToGroup(user, group);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
+            return;
+        }
+        fail();
+    }
+
+    /**
+     * Adds a user to a group where the user does not exist. Verifies that an
+     * exception occurs.
+     * 
+     */
+    public void testAddUserToGroupUnknownGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        Group group2 = new Group(GROUP2);
+        try {
+            _admin.addUserToGroup(user, group2);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
+            return;
+        }
+        fail();
+    }
+
+    /**
+     * Removes a user from a group. Verifies that the user is removed from the
+     * group using several API calls. Verifies that an exception occurs if the
+     * user not part of the group or if the user is only part of one group.
+     */
+    public void testRemoveUserFromGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+
+        User user = _admin.createUser(USER1, PASS1, group);
+        Group group2 = _admin.createGroup(GROUP2);
+        _admin.addUserToGroup(user, group2);
+        Set<Group> groups = user.getGroups();
+        assertEquals(2, groups.size());
+        assertTrue(groups.contains(group));
+        assertTrue(groups.contains(group2));
+
+        _admin.removeUserFromGroup(user, group);
+        groups = user.getGroups();
+        assertEquals(1, groups.size());
+        assertTrue(groups.contains(group2));
+        assertFalse(groups.contains(group));
+    }
+
+    /**
+     * Removes a user from a group where the user is not known. Verifies that an
+     * exception is thrown.
+     * 
+     */
+    public void testRemoveUserFromGroupUnknownUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = createUser(USER1, GROUP1, group);
+        try {
+            _admin.removeUserFromGroup(user, group);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
+        }
+    }
+
+    /**
+     * Removes a user from a group where the group is not known. Verifies that
+     * an exception is thrown.
+     * 
+     */
+    public void testRemoveUserFromGroupUnknownGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        Group group2 = new Group(GROUP2);
+        try {
+            _admin.removeUserFromGroup(user, group2);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
+        }
+    }
+
+    /**
+     * Removes a user from a group where the user is only part of one group.
+     * Verifies that an exception is thrown.
+     */
+    public void testRemoveUserFromGroupOnlyGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        try {
+            _admin.removeUserFromGroup(user, group);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP, e
+                    .getReason());
+        }
+    }
+
+    /**
+     * Gets the list of users and groups. Verifies that the correct suers and
+     * groups are returned. Verifies also that the relations from user to group
+     * are correct.
+     * 
+     */
+    public void testGetUsersAndGroups() throws UserMgtException {
+        Group group1 = _admin.createGroup(GROUP1);
+        Group group2 = _admin.createGroup(GROUP2);
+
+        User user1 = _admin.createUser(USER1, PASS1, group1);
+        _admin.addUserToGroup(user1, group2);
+        User user2 = _admin.createUser(USER2, PASS2, group2);
+
+        Set<User> users = _admin.getUsers();
+        assertEquals(2, users.size());
+        assertTrue(users.contains(user1));
+        assertTrue(users.contains(user2));
+
+        Set<Group> groups = _admin.getGroups();
+        assertEquals(2, groups.size());
+        assertTrue(groups.contains(group1));
+        assertTrue(groups.contains(group2));
+
+        assertTrue(user1.isInGroup(group1));
+        assertTrue(user1.isInGroup(group2));
+        assertFalse(user2.isInGroup(group1));
+        assertTrue(user2.isInGroup(group2));
+
+        Set<Group> groups1 = user1.getGroups();
+        assertEquals(2, groups1.size());
+
+        Set<Group> groups2 = user2.getGroups();
+        assertEquals(1, groups2.size());
+    }
+
+    /**
+     * Renames a user. Verifies that the user is renamed. Verifies that
+     * exceptions are thrown when an attempt is made to rename the user to
+     * itself or to another existing user, or when the group does not exist.
+     * 
+     */
+    public void testRenameUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user1 = _admin.createUser(USER1, PASS1, group);
+        _admin.renameUser(user1, USER2);
+        assertEquals(USER2, user1.getName());
+        assertEquals(user1, _admin.getUser(USER2));
+
+        _admin.createUser(USER1, PASS1, group);
+
+        try {
+            _admin.renameUser(user1, USER1);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.DUPLICATE_USER, e.getReason());
+
+            // do a trivial reanem
+            try {
+                _admin.renameUser(user1, user1.getName());
+            } catch (UserMgtException e2) {
+                assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
+                        .getReason());
+                return;
+            }
+            fail();
+        }
+        fail();
+    }
+
+    /**
+     * Renames a user to a user with an invalid username. Verifies that the
+     * appropriate exception is thrown.
+     * 
+     */
+    public void testRenameUserInvalidUsername() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user1 = _admin.createUser(USER1, PASS1, group);
+        try {
+            _admin.renameUser(user1, USER2);
+        } catch (UserMgtException e) {
+            assertEquals(e.getReason(), Reason.INVALID_USERNAME);
+        }
+    }
+
+    /**
+     * Renames a group. Verifies that the group is renamed. Verifies that
+     * exceptions are thrown when an attempt is made to rename the group to
+     * itself or to another existing group or when the group does not exist.
+     * 
+     */
+    public void testRenameGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        _admin.renameGroup(group, GROUP2);
+        assertEquals(GROUP2, group.getName());
+        assertEquals(group, _admin.getGroup(GROUP2));
+
+        _admin.createGroup(GROUP1);
+        try {
+            _admin.renameGroup(group, GROUP1);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason());
+
+            // do a trivial reanem
+            try {
+                _admin.renameGroup(group, group.getName());
+            } catch (UserMgtException e2) {
+                assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2
+                        .getReason());
+                return;
+            }
+            fail();
+            return;
+        }
+        fail();
+    }
+
+    /**
+     * Renames a group to a group with an invalid name. Verifies that the
+     * appropriate exception is thrown.
+     * 
+     */
+    public void testRenameGroupInvalidGroupname() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        try {
+            _admin.renameGroup(group, "a b");
+        } catch (UserMgtException e) {
+            assertEquals(e.getReason(), Reason.INVALID_GROUPNAME);
+        }
+    }
+
+    /**
+     * Removes a user. Verifies that the user is removed. Verifies that the an
+     * exception is thrown when the user does not exist.
+     * 
+     */
+    public void testRemoveUser() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+
+        assertEquals(1, _admin.getUserCount());
+        _admin.removeUser(user);
+        assertEquals(0, _admin.getUserCount());
+
+        _admin.createUser(USER1, PASS1, group);
+        assertEquals(1, _admin.getUserCount());
+
+        User user2 = createUser(USER2, PASS2, group);
+
+        try {
+            _admin.removeUser(user2);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason());
+        }
+    }
+
+    /**
+     * Removes a group. Verifies that the group is removed. Verifies that the an
+     * exception is thrown when the group does not exist or if there are still
+     * users in the group.
+     * 
+     */
+    public void testRemoveGroup() throws UserMgtException {
+        Group group1 = _admin.createGroup(GROUP1);
+        assertEquals(1, _admin.getGroupCount());
+        _admin.removeGroup(group1);
+        assertEquals(0, _admin.getGroupCount());
+        group1 = _admin.createGroup(GROUP1);
+
+        _admin.createUser(USER1, PASS1, group1);
+        try {
+            _admin.removeGroup(group1);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, e
+                    .getReason());
+            return;
+        }
+        fail();
+    }
+
+    /**
+     * Tries to remove an unknown group. Verifies that an exception is thrown.
+     * 
+     */
+    public void testRemoveGroupUnknownGroup() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        Group group2 = new Group(GROUP2);
+        try {
+            _admin.removeGroup(group2);
+        } catch (UserMgtException e) {
+            assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason());
+        }
+    }
+
+    /**
+     * Changes the password, verifies that this succeeds.
+     * 
+     * @throws UserMgtException
+     */
+    public void testChangePassword() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        User user = _admin.createUser(USER1, PASS1, group);
+        user.changePassword(PASS1, PASS2);
+
+        // retrieve the user and verifies the password hasn't changed.
+        User user2 = _admin.getUser(USER1);
+        try {
+            user2.checkPassword(PASS2);
+            fail(); // password should not have changed already.
+        } catch (UserMgtException e) {
+            // ok.
+        }
+
+        // now notify the admin of the change in the user
+        _admin.userModified(user);
+
+        user2 = _admin.getUser(USER1);
+        user2.checkPassword(PASS2); // this time it should succeed.
+
+    }
+
+    /**
+     * Performance test. Finds a user by name.
+     * 
+     */
+    public void testPerformanceFindUserByName() throws UserMgtException {
+        Group group = _admin.createGroup(GROUP1);
+        _admin.createUser(USER1, PASS1, group);
+
+        int n = 1000;
+        long time = System.currentTimeMillis();
+        for (int i = 0; i < n; i++) {
+            _admin.getUser(USER1);
+        }
+        LOGGER.info("Looked up a user " + n + " times in "
+                + (float) (System.currentTimeMillis() - time) / 1000.0);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java
new file mode 100644 (file)
index 0000000..07a376c
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright 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.wamblee.usermgt;
+
+import org.wamblee.security.encryption.Md5HexMessageDigester;
+import org.wamblee.usermgt.UserMgtException.Reason;
+
+/**
+ * User management test utilities. 
+ *
+ * @author Erik Brakkee
+ */
+public class UsermgtTestUtils {
+    
+    private static final String DUMMY_GROUP = "dummygroup";
+    private static final String DUMMY_PASSWD = "dummypasswd";
+
+    public static Group createGroup(String aName) { 
+        return new Group(aName);
+    }
+    
+    public static User createUser(String aUsername) throws UserMgtException { 
+        return createUser(aUsername, DUMMY_GROUP);
+    }
+    
+    public static User createUser(String aUsername, String aGroup) throws UserMgtException { 
+        return createUser(aUsername, createGroup(aGroup)); 
+    }
+    
+    public static User createUser(String aUsername, Group aGroup) throws UserMgtException { 
+        return createUser(aUsername, DUMMY_PASSWD, aGroup);
+    }
+    
+    public static User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { 
+        return new User(aName, aPassword, aGroup, 
+                new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, 
+                        Reason.INVALID_PASSWORD, "Password must be at least 6 chars"), 
+                        new Md5HexMessageDigester()); 
+    }
+    
+    public static void addUserToGroup(User aUser, Group aGroup) throws UserMgtException { 
+        aUser.addGroup(aGroup);
+    }
+    
+    public static void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException { 
+        aUser.removeGroup(aGroup);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java
new file mode 100644 (file)
index 0000000..fa80b1a
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.component.DatabaseTesterComponent;
+import org.wamblee.test.spring.TestTransactionCallback;
+import org.wamblee.usermgt.GroupSet;
+import org.wamblee.usermgt.InMemoryGroupSetTest;
+
+/**
+ * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet} 
+ *
+ * @author Erik Brakkee
+ */
+public class HibernateGroupSetTest extends InMemoryGroupSetTest {
+    
+    private static final String GROUP_TABLE = "GROUPS"; 
+    
+    private static final String GROUP_QUERY = "select * from " + GROUP_TABLE + " where name = ?";
+    
+    private DefaultContainer _container;
+    private Scope _scope;
+    
+    private DatabaseTesterComponent _databaseTester;
+    private GroupSet _groupSet; 
+    
+    @Override
+    protected void setUp() throws Exception {
+        
+        _container = new UserMgtRepositoryTestContainer("top");
+        
+        ObjectConfiguration config = new ObjectConfiguration(
+                HibernateGroupSetTest.class);
+        config.getSetterConfig().clear().add(
+                "setGroupSet").add("setDatabaseTester");
+        _container.addComponent("testcase", this, config);
+
+        _scope = _container.start();
+
+        _databaseTester.cleanDatabase();
+        super.setUp();
+    }
+
+    @Override
+    protected void tearDown() throws Exception { 
+        _container.stop(_scope);
+       super.tearDown();
+    }
+    
+    public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
+        _databaseTester = aDatabaseTester;
+    }
+   
+    public void setGroupSet(GroupSet aGroupSet) {
+        _groupSet = aGroupSet;
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
+     */
+    @Override
+    protected void checkGroupCount(int aSize) throws SQLException {
+        _databaseTester.flush(); 
+        super.checkGroupCount(aSize);
+        assertEquals(aSize, _databaseTester.getTableSize(GROUP_TABLE));
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
+     */
+    @Override
+    protected void checkGroupExists(final String aGroup) throws SQLException {
+        _databaseTester.flush();
+        Map<String,Integer> result = 
+        _databaseTester.executeTransaction(new TestTransactionCallback()  { 
+            /* (non-Javadoc)
+             * @see org.wamblee.test.TestTransactionCallback#execute()
+             */
+            @Override
+            public Map execute() throws Exception {
+                ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
+                Map<String,Integer> res = new HashMap<String,Integer>(); 
+                res.put("result", _databaseTester.countResultSet(result));
+                return res; 
+            }
+        }); 
+      
+        int count = result.get("result");
+        assertEquals(1, count);
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
+     */
+    @Override
+    protected void checkGroupNotExists(String aGroup) throws SQLException {
+       _databaseTester.flush(); 
+       ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup); 
+       assertEquals(0, _databaseTester.countResultSet(result));
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet()
+     */
+    @Override
+    protected GroupSet createGroupSet() {
+        return _groupSet; 
+    }
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java
new file mode 100644 (file)
index 0000000..f707dba
--- /dev/null
@@ -0,0 +1,146 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+import java.sql.SQLException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wamblee.cache.EhCache;
+import org.wamblee.system.adapters.ClassConfiguration;
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.components.DatabaseComponentFactory;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.component.DatabaseTesterComponent;
+import org.wamblee.system.spring.component.DatasourceComponent;
+import org.wamblee.test.spring.TestTransactionCallbackWithoutResult;
+import org.wamblee.usermgt.UserAdministration;
+import org.wamblee.usermgt.UserAdministrationImplTest;
+
+/**
+ * User administration tests with persistence based on Hibernate. This executes
+ * the same test cases as {@link org.wamblee.usermgt.UserAdministrationImplTest}
+ * with in addition, one test case that executes all Hibernate test cases
+ * separately with each test case in its own transaction.
+ *
+ * @author Erik Brakkee
+ */
+public class HibernateUserAdministrationTest extends UserAdministrationImplTest {
+    
+    private static final Log LOG = LogFactory.getLog(HibernateUserAdministrationTest.class);
+
+    private DefaultContainer _container;
+    private Scope _scope;
+    
+    private DatabaseTesterComponent _databaseTester;
+    private EhCache<Serializable, Serializable> _userCache;
+    private UserAdministration _userAdmin; 
+    
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.usermgt.UserAdministrationImplTest#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        
+        _container = new DefaultContainer("top");
+        DatabaseComponentFactory.addDatabaseConfig(_container);
+        _container.addComponent(new DatasourceComponent("datasource"));
+        _container.addComponent(new UserAdministrationComponent("admin", true));
+        
+        ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class); 
+        dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
+        _container.addComponent("databaseTester", dbtesterConfig);
+        
+        ObjectConfiguration config = new ObjectConfiguration(
+                HibernateUserAdministrationTest.class);
+        config.getSetterConfig().clear().add(
+                "setUserCache").add("setDatabaseTester").add("setUserAdmin");
+        _container.addComponent("testcase", this, config);
+
+        _scope = _container.start();
+
+        _databaseTester.cleanDatabase();
+       
+        super.setUp();
+        clearUserCache();
+    }
+    
+    public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
+        _userCache = aUserCache;
+    }
+    
+    public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
+        _databaseTester = aDatabaseTester;
+    }
+    
+    public void setUserAdmin(UserAdministration aUserAdmin) {
+        _userAdmin = aUserAdmin;
+    }
+
+    @Override
+    protected void tearDown()  throws Exception { 
+        _container.stop(_scope);
+        super.tearDown();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.UserAdministrationImplTest#createAdmin()
+     */
+    @Override
+    protected UserAdministration createAdmin() {
+        return _userAdmin;
+    }
+
+    public void testAllTestsInASeparateTransaction() throws SQLException {
+
+        Method[] methods = UserAdministrationImplTest.class.getMethods();
+        for (final Method method : methods) {
+            if (method.getName().startsWith("test")) {
+                _databaseTester.cleanDatabase();
+                clearUserCache();
+                _databaseTester.executeTransaction(new TestTransactionCallbackWithoutResult() {
+                    public void execute() throws Exception {
+                        LOG.info("Running test " + method.getName());
+                        try {
+                            method.invoke(HibernateUserAdministrationTest.this);
+                        } catch (Throwable t) {
+                            LOG.error("Test " + method.getName() + " failed");
+                            throw new RuntimeException(t.getMessage(), t); 
+                        }
+                        finally {
+                            LOG.info("Test " + method.getName() + " finished");
+                        }
+
+                    }
+                });
+            }
+        }
+    }
+
+    /**
+     * 
+     */
+    private void clearUserCache() {
+        _userCache.clear();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java
new file mode 100644 (file)
index 0000000..82588b3
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.io.Serializable;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Set;
+
+import org.wamblee.cache.EhCache;
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.component.DatabaseTesterComponent;
+import org.wamblee.usermgt.Group;
+import org.wamblee.usermgt.GroupSet;
+import org.wamblee.usermgt.InMemoryUserSetTest;
+import org.wamblee.usermgt.User;
+import org.wamblee.usermgt.UserMgtException;
+import org.wamblee.usermgt.UserSet;
+
+/**
+ * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet}
+ * 
+ * @author Erik Brakkee
+ */
+public class HibernateUserSetTest extends InMemoryUserSetTest {
+
+    private static final String USER_TABLE = "USERS";
+    private static final String GROUP_TABLE = "GROUPS";
+
+    private static final String USER_QUERY = "select * from " + USER_TABLE
+            + " where name = ?";
+    private static final String GROUP_QUERY = "select * from " + GROUP_TABLE
+            + " where name = ?";
+
+    private DefaultContainer _container;
+    private Scope _scope;
+    
+    private UserSet _userset;
+    private GroupSet _groupset;
+    private EhCache<Serializable, Serializable> _userCache;
+    private DatabaseTesterComponent _databaseTester;
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryUserSetTest#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+
+        _container = new UserMgtRepositoryTestContainer("top");
+       
+        ObjectConfiguration config = new ObjectConfiguration(
+                HibernateUserSetTest.class);
+        config.getSetterConfig().clear().add("setUserset").add(
+                "setGroupset").add("setDatabaseTester").add("setUserCache");
+        _container.addComponent("testcase", this, config);
+
+        _scope = _container.start();
+
+        clearUserCache();
+        _databaseTester.cleanDatabase();
+        
+        super.setUp();
+    }
+
+    public void setUserset(UserSet aUserset) {
+        _userset = aUserset;
+    }
+
+    public void setGroupset(GroupSet aGroupset) {
+        _groupset = aGroupset;
+    }
+
+    public void setUserCache(EhCache<Serializable, Serializable> aUserCache) {
+        _userCache = aUserCache;
+    }
+
+    public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) {
+        _databaseTester = aDatabaseTester;
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        _container.stop(_scope);
+        super.tearDown();
+    }
+
+    /**
+     * Clears the user cache.
+     */
+    private void clearUserCache() {
+        _userCache.clear();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
+     */
+    @Override
+    protected void checkUserCount(int aSize) throws SQLException {
+        _databaseTester.flush();
+        super.checkUserCount(aSize);
+        assertEquals(aSize, _databaseTester.getTableSize(USER_TABLE));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
+     */
+    @Override
+    protected void checkUserExists(String aUser) throws SQLException {
+        _databaseTester.flush();
+        ResultSet result = _databaseTester.executeQuery(USER_QUERY, aUser);
+        assertEquals(1, _databaseTester.countResultSet(result));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
+     */
+    @Override
+    protected void checkUserNotExists(String aUser) throws SQLException {
+        _databaseTester.flush();
+        ResultSet result = _databaseTester.executeQuery(USER_QUERY, aUser);
+        assertEquals(0, _databaseTester.countResultSet(result));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int)
+     */
+    @Override
+    protected void checkGroupCount(int aSize) throws SQLException {
+        _databaseTester.flush();
+        assertEquals(aSize, _databaseTester.getTableSize(GROUP_TABLE));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String)
+     */
+    @Override
+    protected void checkGroupExists(String aGroup) throws SQLException {
+        _databaseTester.flush();
+
+        ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
+        assertEquals(1, _databaseTester.countResultSet(result));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String)
+     */
+    @Override
+    protected void checkGroupNotExists(String aGroup) throws SQLException {
+        _databaseTester.flush();
+        ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup);
+        assertEquals(0, _databaseTester.countResultSet(result));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet()
+     */
+    @Override
+    protected UserSet createUserSet() {
+        return _userset;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.usermgt.InMemoryUserSetTest#createGroupSet()
+     */
+    @Override
+    protected GroupSet createGroupSet() {
+        return _groupset;
+    }
+
+    /**
+     * Reproduction of a bug. Create a user which is in group1 Add it to a
+     * second group group2. Remove the user from group1. Verify the user is in
+     * group2.
+     */
+    public void testVerifyAddRemove() throws SQLException, UserMgtException {
+        _databaseTester.cleanDatabase(); // just to be sure.
+        GroupSet groups = getGroups();
+        assertEquals(0, groups.size());
+        Group group1 = createGroup("group1");
+        Group group2 = createGroup("group2");
+        groups.add(group1);
+        groups.add(group2);
+        checkGroupExists("group1");
+        checkGroupExists("group2");
+
+        User user = createUser("user", PASSWORD, group1);
+        getUsers().add(user);
+        checkUserExists("user");
+
+        addUserToGroup(user, group2);
+        getUsers().userModified(user);
+        clearUserCache();
+        User user2 = getUsers().find("user");
+        Set<Group> userGroups = user2.getGroups();
+        assertTrue(user2.isInGroup("group1"));
+        assertTrue(user2.isInGroup("group2"));
+        assertEquals(2, userGroups.size());
+
+        removeUserFromGroup(user, group1);
+        getUsers().userModified(user);
+        clearUserCache();
+        user2 = getUsers().find("user");
+        userGroups = user2.getGroups();
+        assertFalse(user2.isInGroup("group1"));
+        assertTrue(user2.isInGroup("group2"));
+        assertEquals(1, userGroups.size());
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java b/tags/wamblee-utils-0.2.1/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java
new file mode 100644 (file)
index 0000000..dd44391
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright 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.wamblee.usermgt.hibernate;
+
+import java.io.IOException;
+
+import org.wamblee.system.adapters.ClassConfiguration;
+import org.wamblee.system.adapters.DefaultContainer;
+import org.wamblee.system.adapters.ObjectConfiguration;
+import org.wamblee.system.components.DatabaseComponentFactory;
+import org.wamblee.system.spring.component.DatabaseTesterComponent;
+import org.wamblee.system.spring.component.DatasourceComponent;
+import org.wamblee.system.spring.component.HibernateComponent;
+import org.wamblee.usermgt.UserGroupRepositoryComponent;
+
+/**
+ * 
+ * Test container for repository tests of user management.
+ * 
+ * @author Erik Brakkee
+ */
+public class UserMgtRepositoryTestContainer extends DefaultContainer {
+
+    public UserMgtRepositoryTestContainer(String aName) throws IOException {
+        super(aName);
+        DatabaseComponentFactory.addDatabaseConfig(this);
+        addComponent(new DatasourceComponent("datasource"));
+        
+        ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); 
+        mappingFilesConfig.getSetterConfig().initAllSetters();
+        addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig);
+        addComponent(new HibernateComponent("hibernate"));
+        addComponent(new UserGroupRepositoryComponent("usersgroups"));
+        ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class); 
+        dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters();
+        addComponent("databaseTester", dbtesterConfig);
+
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/resources/properties/test.org.wamblee.security.database.properties b/tags/wamblee-utils-0.2.1/security/src/test/resources/properties/test.org.wamblee.security.database.properties
new file mode 100644 (file)
index 0000000..bff2ee4
--- /dev/null
@@ -0,0 +1,11 @@
+
+
+# Database properties for test runs in a J2SE environment. 
+
+# See ORMappingConfig.DatabaseType for allowed values
+database.type=MYSQL_INNO_DB
+
+database.driver=com.mysql.jdbc.Driver
+database.url=jdbc:mysql://localhost:3306/test
+database.username=erik
+database.password=abc123
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/resources/properties/test.org.wamblee.security.usermgt.properties b/tags/wamblee-utils-0.2.1/security/src/test/resources/properties/test.org.wamblee.security.usermgt.properties
new file mode 100644 (file)
index 0000000..aa84735
--- /dev/null
@@ -0,0 +1,5 @@
+
+##############################################################################
+# Name of the administrators group
+##############################################################################
+org.wamblee.security.admingroup=administrators
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.datasource.xml b/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.datasource.xml
new file mode 100644 (file)
index 0000000..d718334
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
+
+    <!-- This is the Spring configuration to define the database-related stuff for the
+    all persistence tests.  -->
+    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
+        <!-- driver classname no longer needed because ServiceLoader is used these days
+        <property name="driverClassName">
+            <value>${database.driver}</value>
+        </property>
+        --> 
+        <property name="url">
+            <value>${database.url}</value>
+        </property>
+        <property name="username">
+            <value>${database.username}</value>
+        </property>
+        <property name="password">
+            <value>${database.password}</value>
+        </property>
+    </bean>
+</beans>
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.properties.xml b/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.properties.xml
new file mode 100644 (file)
index 0000000..5fa2f72
--- /dev/null
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+ <beans> 
+    
+    <bean id="propertyBean"
+        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
+        <property name="locations">
+            <list>
+                <value>properties/test.org.wamblee.security.hibernate.properties</value>
+                <value>properties/test.org.wamblee.security.usermgt.properties</value>
+                <value>properties/test.org.wamblee.security.database.properties</value>
+            </list>
+        </property>
+    </bean> 
+ </beans>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.useraccessor.xml b/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.useraccessor.xml
new file mode 100644 (file)
index 0000000..e306d63
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+
+<beans>
+    
+    <bean id="org.wamblee.usermgt.UserAccessor"
+        class="org.wamblee.security.authorization.TestUserAccessor">
+        
+    </bean>
+    
+</beans> 
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.usermgtinitializer.xml b/tags/wamblee-utils-0.2.1/security/src/test/resources/spring/test.org.wamblee.security.usermgtinitializer.xml
new file mode 100644 (file)
index 0000000..54c9f36
--- /dev/null
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+ <beans> 
+     
+     <bean id="usermgtInitializer"
+         class="org.wamblee.usermgt.UserAdminInitializer">
+         <constructor-arg><ref local="org.wamblee.usermgt.UserAdministration"/></constructor-arg>
+         <!-- users -->
+         <constructor-arg>
+             <list>
+                 <value>erik</value>
+                 <value>admin</value>
+             </list>
+         </constructor-arg>
+         <!-- groups -->
+         <constructor-arg>
+             <list>
+                 <value>users</value>
+                 <value>${org.wamblee.security.admingroup}</value>
+             </list>
+         </constructor-arg>
+         <!-- passwords -->
+         <constructor-arg>
+             <list>
+                 <value>abc123</value>
+                 <value>abc123</value>
+             </list>
+         </constructor-arg>
+     </bean>
+     
+ </beans>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/support/general/pom.xml b/tags/wamblee-utils-0.2.1/support/general/pom.xml
new file mode 100644 (file)
index 0000000..f003577
--- /dev/null
@@ -0,0 +1,62 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-support-general</artifactId>
+  <packaging>jar</packaging>
+  <name>/support/general</name>
+  <url>http://wamblee.org</url>
+  <dependencies>
+    <dependency>
+      <groupId>oro</groupId>
+      <artifactId>oro</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>commons-logging</groupId>
+      <artifactId>commons-logging</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derby</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derbyclient</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derbynet</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>commons-beanutils</groupId>
+      <artifactId>commons-beanutils</artifactId>
+    </dependency>
+    <!-- should be possible to remove the dependence on log4j -->
+    <dependency>
+      <groupId>log4j</groupId>
+      <artifactId>log4j</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>dom4j</groupId>
+      <artifactId>dom4j</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>net.sf.ehcache</groupId>
+      <artifactId>ehcache</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>jaxen</groupId>
+      <artifactId>jaxen</artifactId>
+    </dependency>
+  </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/Cache.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/Cache.java
new file mode 100644 (file)
index 0000000..15f2c50
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.cache;
+
+import java.io.Serializable;
+
+/**
+ * The <code>Cache</code> interface represents... a cache. 
+ * In some circumstances it is more optimal to implement caching directly in 
+ * the code instead of relying on Hibernate caching methods. This interface abstracts
+ * from the used cache implementation. 
+ * Cache implementations must be thread-safe.  
+ */
+public interface Cache<KeyType extends Serializable, ValueType extends Serializable> {
+
+    /**
+     * Adds a key-value pair to the cache. 
+     * @param aKey Key. 
+     * @param aValue Value. 
+     */
+    void put(KeyType aKey, ValueType aValue); 
+    
+    /**
+     * Retrieves a value from the cache. 
+     * @param aKey Key to retrieve. 
+     * @return Key. 
+     */
+    ValueType get(KeyType aKey);
+    
+    /**
+     * Removes an entry from the cache. 
+     * @param aKey Key to remove the entry for. 
+     */
+    void remove(KeyType aKey); 
+    
+    /**
+     * Removes all entries from the cache. 
+     *
+     */
+    void clear(); 
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/CachedObject.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/CachedObject.java
new file mode 100644 (file)
index 0000000..58daf8c
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright 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.wamblee.cache;
+
+import java.io.Serializable;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Represents a cached object. The object is either retrieved from the cache if
+ * the cache has it, or a call back is invoked to get the object (and put it in
+ * the cache).
+ *
+ * @author Erik Brakkee
+ */
+public class CachedObject<KeyType extends Serializable, ValueType extends Serializable> {
+
+    private static final Logger LOGGER = Logger.getLogger(CachedObject.class);
+
+    /**
+     * Callback invoked to compute an object if it was not found in the cache.
+     * 
+     * @param <T>
+     *            Type of the object
+     */
+    public static interface Computation<Key extends Serializable, Value extends Serializable> {
+        /**
+         * Gets the object. Called when the object is not in the cache.
+         * 
+         * @param aObjectKey
+         *            Id of the object in the cache.
+         * @return Object, must be non-null.
+         */
+        Value getObject(Key aObjectKey);
+    }
+
+    /**
+     * Cache to use.
+     */
+    private Cache<KeyType, ValueType> _cache;
+
+    /**
+     * Key of the object in the cache.
+     */
+    private KeyType _objectKey;
+
+    /**
+     * Computation used to obtain the object if it is not found in the cache.
+     */
+    private Computation<KeyType, ValueType> _computation;
+
+    /**
+     * Constructs the cached object.
+     * 
+     * @param aCache
+     *            Cache to use.
+     * @param aObjectKey
+     *            Key of the object in the cache.
+     * @param aComputation
+     *            Computation to get the object in case the object is not in the
+     *            cache.
+     */
+    public CachedObject(Cache<KeyType, ValueType> aCache, KeyType aObjectKey,
+            Computation<KeyType, ValueType> aComputation) {
+        _cache = aCache;
+        _objectKey = aObjectKey;
+        _computation = aComputation;
+    }
+
+    /**
+     * Gets the object. Since the object is cached, different calls to this
+     * method may return different objects.
+     * 
+     * @return Object.
+     */
+    public ValueType get() {
+        ValueType object = (ValueType) _cache.get(_objectKey); // the used
+                                                                // cache is
+                                                                // thread safe.
+        if (object == null) {
+            // synchronize the computation to make sure that the object is only
+            // computed
+            // once when multiple concurrent threads detect that the entry must
+            // be
+            // recomputed.
+            synchronized (this) {
+                object = (ValueType) _cache.get(_objectKey);
+                if (object == null) {
+                    // No other thread did a recomputation so we must do this
+                    // now.
+                    LOGGER.debug("Refreshing cache for '" + _objectKey + "'");
+                    object = _computation.getObject(_objectKey);
+                    _cache.put(_objectKey, object);
+                }
+            }
+        }
+        return object;
+    }
+
+    /**
+     * Invalidates the cache for the object so that it is recomputed the next
+     * time it is requested.
+     * 
+     */
+    public void invalidate() {
+        _cache.remove(_objectKey);
+    }
+
+    /**
+     * Gets the cache.
+     * 
+     * @return Cache.
+     */
+    public Cache getCache() {
+        return _cache;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/EhCache.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/EhCache.java
new file mode 100644 (file)
index 0000000..6a63186
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * Copyright 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.wamblee.cache;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+
+import net.sf.ehcache.Cache;
+import net.sf.ehcache.CacheException;
+import net.sf.ehcache.CacheManager;
+import net.sf.ehcache.Element;
+
+import org.apache.log4j.Logger;
+import org.wamblee.io.InputResource;
+
+/**
+ * Cache implemented on top of EhCache.
+ *
+ * @author Erik Brakkee
+ */
+public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
+        implements org.wamblee.cache.Cache<KeyType, ValueType> {
+
+    private static final Logger LOGGER = Logger.getLogger(EhCache.class);
+
+    /**
+     * EH Cache manager.
+     */
+    private CacheManager _manager;
+
+    /**
+     * EH cache.
+     */
+    private Cache _cache;
+
+    /**
+     * Constructs a cache based on EHCache.
+     * 
+     * @param aResource
+     *            Resource containing the configuration file for EHCache.
+     * @param aCacheName
+     *            Name of the cache to use. If a cache with this name does not
+     *            exist, one is created based on default settings.
+     * @throws IOException
+     * @throws CacheException
+     */
+    public EhCache(InputResource aResource, String aCacheName)
+            throws IOException, CacheException {
+        InputStream is = aResource.getInputStream();
+        try {
+               _manager = new CacheManager(is);
+            _cache = _manager.getCache(aCacheName);
+            if (_cache == null) {
+                LOGGER.warn("Creating cache '" + aCacheName
+                        + "' because it is not configured");
+                _manager.addCache(aCacheName);
+                _cache = _manager.getCache(aCacheName);
+            }
+            assert _cache != null;
+        } finally {
+            is.close();
+        }
+
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
+     */
+    public void put(KeyType aKey, ValueType aValue) {
+        _cache.put(new Element(aKey, aValue));
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#get(KeyType)
+     */
+    public ValueType get(KeyType aKey) {
+        try {
+            Element element = _cache.get(aKey);
+            if (element == null) {
+                return null;
+            }
+            return (ValueType) element.getValue();
+        } catch (CacheException e) {
+            throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#remove(KeyType)
+     */
+    public void remove(KeyType aKey) {
+        _cache.remove(aKey);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#clear()
+     */
+    public void clear() {
+        _cache.removeAll();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/ForeverCache.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/ForeverCache.java
new file mode 100644 (file)
index 0000000..8b7f8bf
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright 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.wamblee.cache;
+
+import java.io.Serializable;
+import java.util.HashMap;
+
+/**
+ * A very simple cache based on a HashMap, It never expires any entries, and has
+ * no bounds on its size.
+ *
+ * @author Erik Brakkee
+ */
+public class ForeverCache<KeyType extends Serializable, ValueType extends Serializable>
+        implements Cache<KeyType, ValueType> {
+
+    /**
+     * Cached entries.
+     */
+    private HashMap<KeyType, ValueType> _map;
+
+    /**
+     * Constructs the cache.
+     * 
+     */
+    public ForeverCache() {
+        _map = new HashMap<KeyType, ValueType>();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
+     */
+    public synchronized void put(KeyType aKey, ValueType aValue) {
+        _map.put(aKey, aValue);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#get(KeyType)
+     */
+    public synchronized ValueType get(KeyType aKey) {
+        return _map.get(aKey);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#remove(KeyType)
+     */
+    public synchronized void remove(KeyType aKey) {
+        _map.remove(aKey);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.cache.Cache#clear()
+     */
+    public synchronized void clear() {
+        _map.clear();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/ZeroCache.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/ZeroCache.java
new file mode 100644 (file)
index 0000000..55f9cc9
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright 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.wamblee.cache;
+
+import java.io.Serializable;
+
+/**
+ * A cache that does not cache. This implementation is useful for disabling caching. 
+ * Because of this implementation, application code does not need to distinguish 
+ * between the situation where it a cache is used and where it isn't. 
+ *
+ * @author Erik Brakkee
+ */
+public class ZeroCache<KeyType extends Serializable, ValueType extends Serializable> 
+   implements Cache<KeyType, ValueType> {
+
+    public ZeroCache() { 
+        // Empty. 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
+     */
+    public void put(KeyType aKey, ValueType aValue) {
+        // Empty.    
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.cache.Cache#get(KeyType)
+     */
+    public ValueType get(KeyType aKey) {
+        return null;
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.cache.Cache#remove(KeyType)
+     */
+    public void remove(KeyType aKey) {
+        // Empty   
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.cache.Cache#clear()
+     */
+    public void clear() {
+        // Empty   
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/cache/package.html
new file mode 100644 (file)
index 0000000..17bde14
--- /dev/null
@@ -0,0 +1,16 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides an interface for a cache together with several 
+implementations. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java
new file mode 100644 (file)
index 0000000..75cdcb1
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright 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.wamblee.collections;
+
+import java.util.Collection;
+
+import org.wamblee.conditions.Condition;
+
+public class CollectionFilter {
+
+    /**
+     * Filters a collection by adding all elements in the from collection 
+     * that satisfy a given condition to the to collection. 
+     * @param <T> Type of contained element. 
+     * @param aFrom From container to which the condition is applied. 
+     * @param aTo To container to which matching elements are added. 
+     * @param aCondition Condition by which elements are matched. 
+     */
+       public static <T> void filter(Collection<T> aFrom, Collection<T> aTo, Condition<T> aCondition) { 
+               for (T t: aFrom) { 
+                       if ( aCondition.matches(t)) { 
+                               aTo.add(t);
+                       }
+               }
+       }
+       
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java
new file mode 100644 (file)
index 0000000..2fe0d11
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright 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.wamblee.concurrency;
+
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * In memory JVM lock. 
+ *
+ * @author Erik Brakkee
+ */ 
+public class JvmLock implements Lock {
+    
+    /**
+     * Reentrant lock to use. 
+     */
+    private ReentrantLock _lock; 
+    
+    /**
+     * In-memory lock. 
+     */
+    public JvmLock() { 
+        _lock = new ReentrantLock(true);     
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.concurrency.Lock#acquire()
+     */
+    public void acquire() {
+        _lock.lock();
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.concurrency.Lock#release()
+     */
+    public void release() {
+        _lock.unlock();       
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/Lock.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/Lock.java
new file mode 100644 (file)
index 0000000..50cc784
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 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.wamblee.concurrency;
+
+/**
+ * Represents a re-entrant lock. 
+ * Implementations can provide inmemory JVM locking or full cluster safe locking 
+ * mechanisms.  
+ *
+ * @author Erik Brakkee
+ */
+public interface Lock {
+    /**
+     * Acquires the lock. 
+     */
+    void acquire(); 
+    
+    /**
+     * Releases the lock. 
+     */
+    void release(); 
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java
new file mode 100644 (file)
index 0000000..e765816
--- /dev/null
@@ -0,0 +1,149 @@
+/*
+ * Copyright 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.wamblee.concurrency;
+
+import java.util.HashSet;
+
+
+/**
+ * Read-write lock for allowing multiple concurrent readers or at most one
+ * writer. This implementation does not aim for high performance but for
+ * robustness and simplicity. Users of this class should not synchronize on
+ * objects of this class.
+ */
+public class ReadWriteLock {
+    /**
+     * Sets containing the references to the threads that are currently
+     * reading. This administration is useful to check that the lock has
+     * already been  acquired before it is release. This check adds robustness
+     * to the application.
+     */
+    private HashSet<Thread> _readers;
+
+    /**
+     * The thread that has acquired the lock for writing or null if no such
+     * thread exists currently.
+     */
+    private Thread _writer;
+
+    /**
+     * Constructs read-write lock.
+     */
+    public ReadWriteLock() {
+        _readers     = new HashSet<Thread>();
+        _writer      = null;
+    }
+
+    /**
+     * Acquires the lock for reading. This call will block until the lock can
+     * be acquired.
+     *
+     * @throws IllegalStateException Thrown if the read or  write lock is
+     *         already acquired.
+     */
+    public synchronized void acquireRead() {
+        if (_readers.contains(Thread.currentThread())) {
+            throw new IllegalStateException(
+                "Read lock already acquired by current thread: "
+                + Thread.currentThread());
+        }
+
+        if (_writer == Thread.currentThread()) {
+            throw new IllegalStateException(
+                "Trying to acquire the read lock while already holding a write lock: "
+                + Thread.currentThread());
+        }
+
+        while (_writer != null) {
+            try {
+                wait();
+            } catch (InterruptedException e) {
+                notifyAll();
+            }
+        }
+
+        _readers.add(Thread.currentThread());
+    }
+
+    /**
+     * Releases the lock for reading. Note: This implementation assumes that
+     * the lock has already been acquired for reading previously.
+     *
+     * @throws IllegalStateException Thrown when the lock was not acquired by
+     *         this thread.
+     */
+    public synchronized void releaseRead() {
+        if (!_readers.remove(Thread.currentThread())) {
+            throw new IllegalStateException(
+                "Cannot release read lock because current thread has not acquired it.");
+        }
+
+        if (_readers.size() == 0) {
+            notifyAll();
+        }
+    }
+
+    /**
+     * Acquires the lock for writing. This call will block until the lock has
+     * been acquired.
+     *
+     * @throws IllegalStateException Thrown if the read or write lock is
+     *         already acquired.
+     */
+    public synchronized void acquireWrite() {
+        if (_writer == Thread.currentThread()) {
+            throw new IllegalStateException(
+                "Trying to acquire a write lock while already holding the write lock: "
+                + Thread.currentThread());
+        }
+
+        if (_readers.contains(Thread.currentThread())) {
+            throw new IllegalStateException(
+                "Trying to acquire a write lock while already holding the read lock: "
+                + Thread.currentThread());
+        }
+
+        // wait until there are no more writers and no more
+        // readers 
+        while ((_writer != null) || (_readers.size() > 0)) {
+            try {
+                wait();
+            } catch (InterruptedException e) {
+                notifyAll();
+            }
+        }
+
+        _writer = Thread.currentThread();
+
+        // notification not necessary since all writers and
+        // readers are now blocked by this thread.
+    }
+
+    /**
+     * Releases the lock for writing.
+     *
+     * @throws IllegalStateException Thrown when the lock was not acquired.
+     */
+    public synchronized void releaseWrite() {
+        if (_writer != Thread.currentThread()) {
+            throw new IllegalStateException(
+                "Cannot release write lock because it was not acquired. ");
+        }
+
+        _writer = null;
+        notifyAll();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/concurrency/package.html
new file mode 100644 (file)
index 0000000..405a12a
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides utilities for dealing with concurrency. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/AndCondition.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/AndCondition.java
new file mode 100644 (file)
index 0000000..5089873
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Represents a logical and of different boolean conditions.
+ *
+ * @author Erik Brakkee
+ */
+public class AndCondition<T> implements Condition<T> {
+
+    private List<Condition<T>> _conditions;
+
+    /**
+     * Constructs the condition.
+     * 
+     * @param aCondition1
+     *            First condition.
+     * @param aCondition2
+     *            Second condition.
+     */
+    public AndCondition(Condition<T> aCondition1, Condition<T> aCondition2) {
+        _conditions = new ArrayList<Condition<T>>();
+        _conditions.add(aCondition1);
+        _conditions.add(aCondition2);
+    }
+
+    /**
+     * Constructs the and condition.
+     * 
+     * @param aConditions
+     *            List of conditions to use in the logical and.
+     */
+    public AndCondition(List<Condition<T>> aConditions) {
+        _conditions = aConditions;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
+     */
+    public boolean matches(T aObject) {
+        for (Condition<T> condition : _conditions) {
+            if (!condition.matches(aObject)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/Condition.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/Condition.java
new file mode 100644 (file)
index 0000000..bf4c217
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+
+/**
+ * Determines if an object matches a certain condition.
+ *
+ * @author Erik Brakkee
+ */
+public interface Condition<T> {
+
+    /**
+     * Determines if an object matches a condition. 
+     * @param aObject object to match. 
+     * @return True iff the object matches. 
+     */
+    boolean matches(T aObject); 
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java
new file mode 100644 (file)
index 0000000..eff83b1
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+/**
+ * Condition which always returns a fixed value. 
+ *
+ * @author Erik Brakkee
+ */
+public class FixedCondition<T> implements Condition<T> {
+    
+    private boolean _value; 
+    
+    /**
+     * Constructs the condition. 
+     * @param aValue Fixed value of the condition. 
+     */
+    public FixedCondition(boolean aValue) { 
+        _value = aValue; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.conditions.Condition#matches(T)
+     */
+    public boolean matches(T aObject) {
+        return _value; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/OrCondition.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/OrCondition.java
new file mode 100644 (file)
index 0000000..0840c78
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Represents a logical or of different boolean conditions.
+ *
+ * @author Erik Brakkee
+ */
+public class OrCondition<T> implements Condition<T> {
+
+    private List<Condition<T>> _conditions;
+
+    /**
+     * Constructs the condition.
+     * 
+     * @param aCondition1
+     *            First condition.
+     * @param aCondition2
+     *            Second condition.
+     */
+    public OrCondition(Condition<T> aCondition1, Condition<T> aCondition2) {
+        _conditions = new ArrayList<Condition<T>>();
+        _conditions.add(aCondition1);
+        _conditions.add(aCondition2);
+    }
+
+    /**
+     * Constructs the or condition.
+     * 
+     * @param aConditions
+     *            List of conditions to use in the logical or.
+     */
+    public OrCondition(List<Condition<T>> aConditions) {
+        _conditions = aConditions;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program)
+     */
+    public boolean matches(T aObject) {
+        for (Condition<T> condition : _conditions) {
+            if (condition.matches(aObject)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java
new file mode 100644 (file)
index 0000000..2ce7a0e
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.beanutils.PropertyUtils;
+
+/**
+ * Condition to check whether a given property value matches a certain 
+ * regular expression.
+ *
+ * @author Erik Brakkee
+ */
+public class PropertyRegexCondition<T> implements Condition<T> {
+    
+    /**
+     * Property name. 
+     */
+    private String _property;
+    
+    /**
+     * Regular expression. 
+     */
+    private Pattern _regex;
+    
+    /**
+     * Whether or not to convert the value to lowercase before matching. 
+     */
+    private boolean _tolower; 
+    
+    /**
+     * Constructs the condition. 
+     * @param aProperty Name of the property to examine. 
+     * @param aRegex Regular expression to use. 
+     * @param aTolower Whether or not to convert the value to lowercase before matching. 
+     */
+    public PropertyRegexCondition(String aProperty, String aRegex, boolean aTolower) {
+        _property = aProperty;
+        _regex = Pattern.compile(aRegex);
+        _tolower = aTolower;
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.conditions.Condition#matches(T)
+     */
+    public boolean matches(T aObject) {
+        try {
+            String value = PropertyUtils.getProperty(aObject, _property) + "";
+            if ( _tolower ) { 
+                value = value.toLowerCase(); 
+            }
+            Matcher matcher = _regex.matcher(value); 
+            return matcher.matches(); 
+        } catch (IllegalAccessException e) {
+            throw new RuntimeException(e.getMessage(), e);
+        } catch (InvocationTargetException e) {
+            throw new RuntimeException(e.getMessage(), e);
+        } catch (NoSuchMethodException e) {
+            throw new RuntimeException(e.getMessage(), e);
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/conditions/package.html
new file mode 100644 (file)
index 0000000..3d489d6
--- /dev/null
@@ -0,0 +1,16 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides some basic support classes for checking boolean conditions
+on objects. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanFactory.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanFactory.java
new file mode 100644 (file)
index 0000000..56844bd
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.general;
+
+/**
+ * Bean factory used to obtain objects in a transparent way. 
+ *
+ * @author Erik Brakkee
+ */
+public interface BeanFactory {
+
+    /**
+     * Finds a bean based on id. 
+     * @param aId Id of the bean. 
+     * @return Object  (always non-null). 
+     * @throws BeanFactoryException In case the object could not be found. 
+     */
+    Object find(String aId);  
+    
+    /**
+     * Finds a bean of the given class and which can be cast to the 
+     * specified class. This is typically used by specifying the interface
+     * class for retrieving an implementation of that class. This 
+     * means that the bean implementing the class is configured in the bean factory
+     * with id equal to the class name of the interface.  
+     * @param aClass Class of the object to find. 
+     * @return Object (always non-null).
+     * @throws BeanFactoryException In case the object could not be found. 
+     */
+     <T> T find(Class<T> aClass);
+     
+     /**
+      * Finds a bean with the given id which can be cast to the specified
+      * class.  
+      * @param <T> Type of the object to get. 
+      * @param aId Id of the object to lookup. 
+      * @param aClass Class that the object must extends. 
+      * @return Object, always non-null. 
+      * @throws BeanFactoryException In case the object could not be found. 
+      */
+     <T> T find(String aId, Class<T> aClass); 
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java
new file mode 100644 (file)
index 0000000..9110db9
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 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.wamblee.general;
+
+/**
+ * Exception thrown by the BeanFactory if an object could not be found. 
+ *
+ * @author Erik Brakkee
+ */
+public class BeanFactoryException extends RuntimeException {
+    static final long serialVersionUID = -1215992188624874902L;
+
+    /**
+     * Constructs the exception. 
+     * @param aMsg Message. 
+     */
+    public BeanFactoryException(String aMsg) { 
+        super(aMsg); 
+    }
+    
+    /**
+     * Constructs the exception. 
+     * @param aMsg Message.
+     * @param aThrowable Cause of the exception.
+     */
+    public BeanFactoryException(String aMsg, Throwable aThrowable) {
+        super(aMsg, aThrowable);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanKernel.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/BeanKernel.java
new file mode 100644 (file)
index 0000000..d05eef3
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * Copyright 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.wamblee.general;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.InputResource;
+
+/**
+ * The standard means to obtain the bean factory. This works by reading a
+ * property {@value #BEAN_FACTORY_CLASS} from a property file named
+ * {@value #BEAN_KERNEL_PROP_FILE} from the class path. This property identifies
+ * the bean factory implementation to use. The configured bean factory must have
+ * a no-arg constructor.
+ */
+public final class BeanKernel {
+
+    private static final Log LOG = LogFactory.getLog(BeanKernel.class);
+
+    /**
+     * Bean factory kernel properties file.
+     */
+    private static final String BEAN_KERNEL_PROP_FILE = "org.wamblee.beanfactory.properties";
+
+    /**
+     * Name of the property to define the name of the bean factory class to use.
+     * THis class must have a public default constructor.
+     */
+    private static final String BEAN_FACTORY_CLASS = "org.wamblee.beanfactory.class";
+
+    /**
+     * Cached bean factory.
+     */
+    private static BeanFactory BEAN_FACTORY;
+
+    /**
+     * Disabled constructor.
+     * 
+     */
+    private BeanKernel() {
+        // Empty
+    }
+
+    /**
+     * Overrides the default mechanism for looking up the bean factory by
+     * specifying it yourself.
+     * 
+     * @param aOverride
+     *            Override bean factory.
+     */
+    public static void overrideBeanFactory(BeanFactory aOverride) {
+        BEAN_FACTORY = aOverride;
+    }
+
+    /**
+     * Gets the bean factory.
+     * 
+     * @return Bean factory.
+     */
+    public static BeanFactory getBeanFactory() {
+        synchronized (BeanFactory.class) {
+            if (BEAN_FACTORY == null) {
+                BEAN_FACTORY = lookupBeanFactory(BEAN_KERNEL_PROP_FILE);
+            }
+        }
+        return BEAN_FACTORY;
+    }
+
+    /**
+     * Lookup the bean factory based on the properties file.
+     * 
+     * @return Bean factory.
+     */
+    static BeanFactory lookupBeanFactory(String aPropertyFilename) {
+        InputResource resource = new ClassPathResource(aPropertyFilename);
+        InputStream is;
+        try {
+            is = resource.getInputStream();
+        } catch (IOException e) {
+            throw new BeanFactoryException("Cannot open resource " + resource,
+                    e);
+        }
+        try {
+            Properties props = new Properties();
+            props.load(is);
+            String className = props.getProperty(BEAN_FACTORY_CLASS);
+            Class beanFactory = Class.forName(className);
+            return (BeanFactory) beanFactory.newInstance();
+        } catch (Exception e) {
+            throw new BeanFactoryException("Cannot read from resource "
+                    + resource, e);
+        } finally {
+            try {
+                is.close();
+            } catch (IOException e) {
+                // last resort cannot do much now.
+                LOG.error("Error closing resource " + resource);
+            }
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java
new file mode 100644 (file)
index 0000000..5275e15
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright 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.wamblee.general;
+
+import java.io.IOException;
+import java.io.File;
+import java.net.URLClassLoader;
+import java.net.URL;
+import java.lang.reflect.Method;
+
+/**
+ * Utility for working with the class loader. Based on the ClassPathHacker
+ * example found on the internet.   
+ */
+public class ClassLoaderUtils {
+    
+    // No logging in this class to keep the required class libraries
+    // limited to the standard java classes. This allows use of the
+    // utilities in an environment with a very limited classpath. 
+
+    private static final String JAR_SUFFIX = ".jar";
+
+    /**
+     * Adds all jars in the given directory to the class path. 
+     * @param aDirectory Directory. 
+     * @throws IOException
+     */
+    public static void addJarsInDirectory(File aDirectory) throws IOException {
+        System.out.println("directory '" + aDirectory + "'");
+
+        for (File aFile : aDirectory.listFiles()) {
+            System.out
+                    .println("Considering '" + aFile.getCanonicalPath() + "'");
+            if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) {
+                System.out.println("Adding '" + aFile.getCanonicalPath()
+                        + "' to classpath.");
+                addFile(aFile);
+            }
+        }
+    }
+
+    /**
+     * Adds a file to the classpath.
+     * @param aFilename Filename to add. 
+     * @throws IOException
+     */
+    public static void addFile(String aFilename) throws IOException {
+        File f = new File(aFilename);
+        addFile(f);
+    }
+
+    /**
+     * Adds a file to the classpath. 
+     * @param aFile File to add. 
+     * @throws IOException
+     */
+    public static void addFile(File aFile) throws IOException {
+        addURL(aFile.toURL());
+    }
+
+    /**
+     * Adds a url to the classpath.
+     * @param aUrl Url to add. 
+     * @throws IOException
+     */
+    public static void addURL(URL aUrl) throws IOException {
+
+        URLClassLoader sysloader = (URLClassLoader) ClassLoader
+                .getSystemClassLoader();
+        Class sysclass = URLClassLoader.class;
+
+        try {
+            Method method = sysclass.getDeclaredMethod("addURL", new Class[]{ URL.class } );
+            method.setAccessible(true);
+            method.invoke(sysloader, new Object[] { aUrl });
+        } catch (Throwable t) {
+            t.printStackTrace();
+            throw new IOException(
+                    "Error, could not add URL to system classloader");
+        }
+
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/Pair.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/Pair.java
new file mode 100644 (file)
index 0000000..2d90387
--- /dev/null
@@ -0,0 +1,80 @@
+
+
+
+/*
+ * Copyright 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.wamblee.general;
+
+/**
+ * Represents a pair of objects. This is inspired on the C++ Standard Template
+ * Library pair template.
+ * 
+ * @param <T>
+ *            Type of the first object.
+ * @param <U>
+ *            Type of the second object.
+ *
+ * @author Erik Brakkee
+ */
+public class Pair<T, U> {
+
+    private T _t;
+
+    private U _u;
+
+    /**
+     * Constructs the pair.
+     * 
+     * @param aT
+     *            First object.
+     * @param aU
+     *            Second object.
+     */
+    public Pair(T aT, U aU) {
+        _t = aT;
+        _u = aU;
+    }
+
+    /**
+     * Copies a pair.
+     * 
+     * @param aPair
+     *            Pair to copy.
+     */
+    public Pair(Pair<T, U> aPair) {
+        _t = aPair._t;
+        _u = aPair._u;
+    }
+
+    /**
+     * Gets the first object of the pair.
+     * 
+     * @return First object.
+     */
+    public T getFirst() {
+        return _t;
+    }
+
+    /**
+     * Gets the second object of the pair.
+     * 
+     * @return Second object.
+     */
+    public U getSecond() {
+        return _u;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/general/package.html
new file mode 100644 (file)
index 0000000..042270f
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides several general purpose support classes. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/ClassPathResource.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/ClassPathResource.java
new file mode 100644 (file)
index 0000000..32014a1
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Represents an input resource in the classpath.
+ */
+public class ClassPathResource implements InputResource {
+    /**
+     * Resource name.
+     */
+    private String _resource;
+
+    /**
+     * Construct the class path resource.
+     * 
+     * @param aResource
+     *            Resource
+     */
+    public ClassPathResource(String aResource) {
+        _resource = aResource;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.io.InputResource#getInputStream()
+     */
+    public InputStream getInputStream() throws IOException {
+        InputStream stream = Thread.currentThread().getContextClassLoader()
+                .getResourceAsStream(_resource);
+        if (stream == null) {
+            throw new IOException("Class path resource '" + _resource
+                    + "' not found.");
+        }
+        return stream;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see java.lang.Object#toString()
+     */
+    public String toString() {
+        return "ClassPathResource(" + _resource + ")";
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java
new file mode 100644 (file)
index 0000000..029f33e
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Monitors a directory for changes.
+ * 
+ * @author Erik Brakkee
+ */
+public class DirectoryMonitor {
+
+       private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
+
+       public static interface Listener {
+               
+               void fileChanged(File aFile);
+
+               void fileCreated(File aFile);
+
+               void fileDeleted(File aFile);
+       };
+
+       private File _directory;
+       private FileFilter _filter;
+       private Listener _listener;
+       private Map<File, Date> _contents;
+
+       public DirectoryMonitor(File aDirectory, FileFilter aFilefilter,
+                       Listener aListener) {
+               _directory = aDirectory;
+               if (!_directory.isDirectory()) {
+                       throw new IllegalArgumentException("Directory '" + _directory
+                                       + "' does not exist");
+               }
+               _filter = aFilefilter;
+               _listener = aListener;
+               _contents = new HashMap<File, Date>();
+       }
+
+       /**
+        * Polls the directory for changes and notifies the listener of any changes. 
+        * In case of any exceptions thrown by the listener while handling the changes, 
+        * the next call to this method will invoked the listeners again for the same changes. 
+        */
+       public void poll() {
+               LOG.debug("Polling " + _directory);
+               Map<File, Date> newContents = new HashMap<File, Date>();
+               File[] files = _directory.listFiles(_filter);
+
+               // Check deleted files. 
+               Set<File> deletedFiles = new HashSet<File>(_contents.keySet());
+               for (File file : files) {
+                       if (file.isFile()) {
+                               if (_contents.containsKey(file)) {
+                                       deletedFiles.remove(file);
+                               }
+                       }
+               }
+               for (File file : deletedFiles) {
+                       _listener.fileDeleted(file);
+               }
+               
+               for (File file : files) {
+                       if (file.isFile()) {
+                               if (_contents.containsKey(file)) {
+                                       Date oldDate = _contents.get(file);
+                                       if (file.lastModified() != oldDate.getTime()) {
+                                               _listener.fileChanged(file);
+                                       } else {
+                                               // No change.
+                                       }
+                                       newContents.put(file, new Date(file.lastModified()));
+                               } else {
+                                       _listener.fileCreated(file);
+                                       newContents.put(file, new Date(file.lastModified()));
+                               }
+                       }
+               }
+               
+               _contents = newContents;
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/FileResource.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/FileResource.java
new file mode 100644 (file)
index 0000000..4f8c0ad
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Resource implemention for reading from a file.
+ *
+ * @author Erik Brakkee
+ */
+public class FileResource implements InputResource {
+    /**
+     * File to read.
+     */
+    private File _file;
+
+    /**
+     * Constructs the resource.
+     * 
+     * @param aFile
+     *            File to read.
+     */
+    public FileResource(File aFile) {
+        _file = aFile;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.io.InputResource#getInputStream()
+     */
+    public InputStream getInputStream() throws IOException {
+        return new BufferedInputStream(new FileInputStream(_file));
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/InputResource.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/InputResource.java
new file mode 100644 (file)
index 0000000..2a0e8cd
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Represents a resource from which information can be read.
+ *
+ * @author Erik Brakkee
+ */
+public interface InputResource {
+    /**
+     * Gets the input stream to the resource. The obtained input stream must be
+     * closed once reading has finished.
+     * 
+     * @return Input stream to the resource, never null.
+     * @throws IOException
+     *             in case the resource cannot be found.
+     */
+    InputStream getInputStream() throws IOException;
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/SimpleProcess.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/SimpleProcess.java
new file mode 100644 (file)
index 0000000..d4f7b16
--- /dev/null
@@ -0,0 +1,168 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class SimpleProcess {
+
+       private static final Log LOG = LogFactory.getLog(SimpleProcess.class);
+
+       private File _directory;
+
+       private String[] _cmd;
+       
+       private String _stdout; 
+       private String _stderr; 
+
+       public SimpleProcess(File aDirectory, String[] aCmd) {
+               _directory = aDirectory;
+               _cmd = aCmd;
+       }
+
+    /**
+     * @return the stdout
+     */
+    public String getStdout() {
+        return _stdout;
+    }
+    
+    /**
+     * @return the stderr
+     */
+    public String getStderr() {
+        return _stderr;
+    }
+    
+       /**
+        * Runs the process and blocks until it is done.
+        * 
+        * @return Exit status of the process.
+        * @throws IOException
+        *             In case of problems.
+        */
+       public int run() throws IOException {
+               return runImpl();
+       }
+
+       private int runImpl() throws IOException {
+               try {
+                   String fullcmd = ""; 
+                   for (String part: _cmd) {
+                       fullcmd += " " + part; 
+                   }
+                       LOG.debug("Executing '" + fullcmd + "' in directory '" + _directory
+                                       + "'");
+                       java.lang.Process proc = Runtime.getRuntime().exec(_cmd, null, _directory);
+
+                       // Read standard output and error in separate threads to avoid
+                       // deadlock.
+
+            StringWriter stdout = new StringWriter();
+            StringWriter stderr = new StringWriter();
+                       Thread stdoutReader = readAndLogStream("STDOUT>  ", proc
+                                       .getInputStream(), stdout);
+                       Thread stderrReader = readAndLogStream("STDERR>  ", proc
+                                       .getErrorStream(), stderr);
+
+                       try {
+                               proc.waitFor();
+                       } catch (InterruptedException e) {
+                               IOException exception = new IOException(
+                                               "Process was terminated: " + this);
+                               exception.initCause(e);
+                               throw exception;
+                       }
+                       waitForReader(stdoutReader);
+                       waitForReader(stderrReader);
+            
+            _stdout = stdout.toString();
+            _stderr = stderr.toString();
+
+                       if (proc.exitValue() != 0) {
+                               LOG.warn("Exit value was non-zero: " + this);
+                       } else { 
+                               LOG.debug("Process finished");
+                       }
+                       return proc.exitValue();
+               } catch (IOException e) {
+                       IOException exception = new IOException("Error executing process: "
+                                       + this);
+                       exception.initCause(e);
+                       throw exception;
+               }
+       }
+
+       private void waitForReader(Thread aReaderThread) {
+               try {
+                       aReaderThread.join();
+               } catch (InterruptedException e) {
+                       LOG
+                                       .warn(this
+                                                       + ": error waiting for output stream reader of process to finish");
+               }
+       }
+
+       private Thread readAndLogStream(final String aPrefix,
+                       final InputStream aStream, final Writer aOutput) {
+               Thread inputReader = new Thread() {
+                       @Override
+                       public void run() {
+                               BufferedReader br = null;
+                               try {
+                                       br = new BufferedReader(new InputStreamReader(aStream));
+                                       String str;
+                                       while ((str = br.readLine()) != null) {
+                                               LOG.debug(aPrefix + str);
+                        aOutput.write(str);
+                                       }
+                               } catch (IOException e) {
+                                       LOG.warn(SimpleProcess.this + ": error reading input stream", e);
+                               } finally {
+                                       if (br != null) {
+                                               try {
+                                                       br.close();
+                                               } catch (IOException e) {
+                                                       LOG.warn("Error closing stream " + aPrefix);
+                                               }
+                                       }
+                               }
+                       }
+               };
+               inputReader.start();
+               return inputReader;
+       }
+
+       @Override
+       public String toString() {
+        String fullcmd = "";
+        for (String part: _cmd) { 
+            fullcmd += part + " ";
+        }
+               return "process(dir = '" + _directory + "', cmd = '" + fullcmd + "')";
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/StreamResource.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/StreamResource.java
new file mode 100644 (file)
index 0000000..e3291ae
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Input resource based on an input stream.
+ *
+ * @author Erik Brakkee
+ */
+public class StreamResource implements InputResource {
+    /**
+     * Input stream to read.
+     */
+    private InputStream _stream;
+
+    /**
+     * Constructs a resource.
+     * 
+     * @param aStream
+     *            Input stream to read.
+     */
+    public StreamResource(InputStream aStream) {
+        _stream = aStream;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see InputResource#getInputStream()
+     */
+    public InputStream getInputStream() throws IOException {
+        return _stream;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/io/package.html
new file mode 100644 (file)
index 0000000..2023c07
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides several support utilities for IO related functionality.
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java
new file mode 100644 (file)
index 0000000..0b14585
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 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.wamblee.observer;
+
+/**
+ * Default observer notifier which calls
+ * {@link org.wamblee.observer.Observer#send(ObservableType, Event)}
+ * immediately.
+ *
+ * @author Erik Brakkee
+ */
+public class DefaultObserverNotifier<ObservableType, Event> implements
+        ObserverNotifier<ObservableType, Event> {
+
+    /**
+     * Constructs the notifier.
+     * 
+     */
+    public DefaultObserverNotifier() {
+        // Empty
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer,
+     *      ObservableType, Event)
+     */
+    public void update(Observer<ObservableType, Event> aObserver,
+            ObservableType aObservable, Event aEvent) {
+        aObserver.send(aObservable, aEvent);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/Observable.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/Observable.java
new file mode 100644 (file)
index 0000000..2980afa
--- /dev/null
@@ -0,0 +1,146 @@
+/*
+ * Copyright 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.wamblee.observer;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.log4j.Logger;
+
+/**
+ * Implements subscription and notification logic for an observer pattern. This
+ * class is thread safe.
+ */
+public class Observable<ObservableType, Event> {
+
+    private static final Logger LOGGER = Logger.getLogger(Observable.class);
+
+    /**
+     * Observable.
+     */
+    private ObservableType _observable;
+
+    /**
+     * Used to notify observers.
+     */
+    private ObserverNotifier<ObservableType, Event> _notifier;
+
+    /**
+     * Map of subscription to observer.
+     */
+    private Map<Long, Observer<ObservableType, Event>> _observers;
+
+    /**
+     * Counter for subscriptions. Holds the next subscription.
+     */
+    private long _counter;
+
+    /**
+     * Constructs the observable.
+     * 
+     * @param aObservable
+     *            Observable this instance is used for.
+     * @param aNotifier
+     *            Object used for implementing notification of listeners.
+     */
+    public Observable(ObservableType aObservable,
+            ObserverNotifier<ObservableType, Event> aNotifier) {
+        _observable = aObservable;
+        _notifier = aNotifier;
+        _observers = new TreeMap<Long, Observer<ObservableType, Event>>();
+        _counter = 0;
+    }
+
+    /**
+     * Subscribe an obvers.
+     * 
+     * @param aObserver
+     *            Observer to subscribe.
+     * @return Event Event to send.
+     */
+    public synchronized long subscribe(Observer<ObservableType, Event> aObserver) {
+        long subscription = _counter++; // integer rage is so large it will
+                                        // never roll over.
+        _observers.put(subscription, aObserver);
+        return subscription;
+    }
+
+    /**
+     * Unsubscribe an observer.
+     * 
+     * @param aSubscription
+     *            Subscription which is used
+     * @throws IllegalArgumentException
+     *             In case the subscription is not known.
+     */
+    public synchronized void unsubscribe(long aSubscription) {
+        Object obj = _observers.remove(aSubscription);
+        if (obj == null) {
+            throw new IllegalArgumentException("Subscription '" + aSubscription
+                    + "'");
+        }
+    }
+
+    /**
+     * Gets the number of subscribed observers.
+     * 
+     * @return Number of subscribed observers.
+     */
+    public int getObserverCount() {
+        return _observers.size();
+    }
+
+    /**
+     * Notifies all subscribed observers.
+     * 
+     * @param aEvent
+     *            Event to send.
+     */
+    public void send(Event aEvent) {
+        // Make sure we do the notification while not holding the lock to avoid
+        // potential deadlock
+        // situations.
+        List<Observer<ObservableType, Event>> observers = new ArrayList<Observer<ObservableType, Event>>();
+        synchronized (this) {
+            observers.addAll(_observers.values());
+        }
+        for (Observer<ObservableType, Event> observer : observers) {
+            _notifier.update(observer, _observable, aEvent);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see java.lang.Object#finalize()
+     */
+    @Override
+    protected void finalize() throws Throwable {
+        if (_observers.size() > 0) {
+            LOGGER
+                    .error("Still observers registered at finalization of observer!");
+            for (Observer observer : _observers.values()) {
+                LOGGER.error("  observer: " + observer);
+            }
+        }
+
+        super.finalize();
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/Observer.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/Observer.java
new file mode 100644 (file)
index 0000000..a0e6431
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 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.wamblee.observer;
+
+/**
+ * This is a type-safe version of {@link java.util.Observable}. 
+ *
+ * @author Erik Brakkee
+ */
+public interface Observer<ObservableType, Event> {
+
+    /**
+     * Called when an event has occurred on the observable.
+     * @param aObservable Observable. 
+     * @param aEvent Event. 
+     */
+    void send(ObservableType aObservable, Event aEvent); 
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java
new file mode 100644 (file)
index 0000000..f09c5f0
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.observer;
+
+/**
+ * Implementation of notification of subscribers. 
+ *
+ * @author Erik Brakkee
+ */
+public interface ObserverNotifier<ObservableType, Event> {
+    
+    /**
+     * Notifies an observer. 
+     *
+     * @param aObserver Observer to notify
+     * @param aObservable Observable at which the event occured. 
+     * @param aEvent Event that occured. 
+     */
+    void update(Observer<ObservableType, Event> aObserver, ObservableType aObservable, Event aEvent);
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/observer/package.html
new file mode 100644 (file)
index 0000000..35b6c3b
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides support for the observer pattern. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java
new file mode 100644 (file)
index 0000000..4eee3a0
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright 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.wamblee.persistence;
+
+import java.io.Serializable;
+
+/**
+ * Default implementation of Persistent. 
+ *
+ * @author Erik Brakkee
+ */
+public abstract class AbstractPersistent implements Persistent {
+    
+    /**
+     * Primary key. 
+     */
+    private Serializable _primaryKey; 
+    
+    /**
+     * Version. 
+     */
+    private int _version; 
+    
+    /**
+     * Constructs the object. 
+     *
+     */
+    protected AbstractPersistent() { 
+        _primaryKey = null; 
+        _version = -1; 
+    }
+    
+    /**
+     * Copy constructor. 
+     * @param aPersistent Object to copy. 
+     */
+    protected AbstractPersistent(AbstractPersistent aPersistent) {
+        _primaryKey = aPersistent._primaryKey; 
+        _version = aPersistent._version; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.persistence.Persistent#getPrimaryKey()
+     */
+    public Serializable getPrimaryKey() {
+        return _primaryKey; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable)
+     */
+    public void setPrimaryKey(Serializable aKey) {
+        _primaryKey = aKey; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.persistence.Persistent#getPersistedVersion()
+     */
+    public int getPersistedVersion() {
+        return _version; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.persistence.Persistent#setPersistedVersion(int)
+     */
+    public void setPersistedVersion(int aVersion) {
+        _version = aVersion;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/Persistent.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/Persistent.java
new file mode 100644 (file)
index 0000000..57faf95
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright 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.wamblee.persistence;
+
+import java.io.Serializable;
+
+/**
+ * Interface for persistent objects. This defines required functionality for all objects
+ * that are persisted. 
+ * 
+ * Objects that implement this interface and which implement 
+ * {@link java.lang.Object#equals(java.lang.Object)}
+ * should exclude the primary key and version from determining equality. 
+ */
+public interface Persistent {
+
+    /**
+     * Gets the primary key. 
+     * @return Primary key.
+     * @see #setPrimaryKey(Serializable) 
+     */
+    Serializable getPrimaryKey(); 
+    
+    /**
+     * Sets the primary key. 
+     * @param aKey Primary key.
+     * @see #getPrimaryKey() 
+     */
+    void setPrimaryKey(Serializable aKey); 
+    
+    /**
+     * Gets the version. 
+     * @return Version. 
+     * @see #setPersistedVersion(int)
+     */
+    int getPersistedVersion(); 
+    
+    /**
+     * Sets the version. 
+     * @param aVersion Version. 
+     * @see #getPersistedVersion()
+     */
+    void setPersistedVersion(int aVersion); 
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/persistence/package.html
new file mode 100644 (file)
index 0000000..cdca295
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides support for persistence. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java
new file mode 100644 (file)
index 0000000..a1fa552
--- /dev/null
@@ -0,0 +1,79 @@
+package org.wamblee.reflection;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class ReflectionUtils {
+
+       /**
+        * Wraps a type by the corresponding wrapper type if it is a primitive
+        * type.
+        * @param aClass Type to wrap. 
+        * @return Wrapped type for primitives or the provided argument value. 
+        */
+       public static Class wrapIfNeeded(Class aClass) {
+
+               if (aClass == boolean.class) {
+                       return Boolean.class;
+               }
+               if (aClass == byte.class) {
+                       return Byte.class;
+               }
+               if (aClass == char.class) {
+                       return Character.class;
+               }
+               if (aClass == short.class) {
+                       return Short.class;
+               }
+               if (aClass == int.class) {
+                       return Integer.class;
+               }
+               if (aClass == long.class) {
+                       return Long.class;
+               }
+               if (aClass == float.class) {
+                       return Float.class;
+               }
+               if (aClass == double.class) {
+                       return Double.class;
+               }
+               if (aClass == void.class) {
+                       return Void.class;
+               }
+               return aClass;
+       }
+       
+       
+       public static List<Method> getAllMethods(Class aClass) {
+               
+               Map<String,Method> found = new HashMap<String, Method>();
+               getAllMethods(aClass, found);
+               return new ArrayList<Method>(found.values());
+       }
+
+       private static void getAllMethods(Class aClass, Map<String,Method> aFound) { 
+               List<Method> declared = Arrays.asList(aClass.getDeclaredMethods());
+               for (Method method: declared) { 
+                       Method superMethod = aFound.get(method.getName());
+                       if ( superMethod == null ) { 
+                               // no superclass method
+                               aFound.put(method.getName(), method);
+                       }
+                       else { 
+                               // super class method. Check for override.
+                               if ( !Arrays.equals(superMethod.getParameterTypes(), method.getParameterTypes())) { 
+                                       // parameters differ so this is a new method.
+                                       aFound.put(method.getName(), method);
+                               }
+                       }
+               }
+               Class superClass = aClass.getSuperclass();
+               if (superClass != null) {
+                       getAllMethods(superClass, aFound);
+               }
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java
new file mode 100644 (file)
index 0000000..ba2d875
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+import java.io.IOException;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.stream.StreamSource;
+
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.InputResource;
+
+/**
+ * URI resolver that resolves stylesheets through the classpath.
+ */
+public class ClasspathUriResolver implements URIResolver {
+
+    /**
+     * Constructs the resolver.
+     * 
+     */
+    public ClasspathUriResolver() {
+        // Empty.
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see javax.xml.transform.URIResolver#resolve(java.lang.String,
+     *      java.lang.String)
+     */
+    public Source resolve(String aHref, String aBase)
+            throws TransformerException {
+        InputResource xslt = new ClassPathResource(aHref);
+        try {
+            return new StreamSource(xslt.getInputStream());
+        } catch (IOException e) {
+            throw new TransformerException(
+                    "Could not get XSLT style sheet in classpath '" + aHref
+                            + "'", e);
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/DomUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/DomUtils.java
new file mode 100644 (file)
index 0000000..3825bac
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.XMLSerializer;
+import org.dom4j.DocumentException;
+import org.dom4j.io.DOMReader;
+import org.dom4j.io.DOMWriter;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+/**
+ * Some basic XML utilities for common reoccuring tasks for DOM documents.
+ *
+ * @author Erik Brakkee
+ */
+public final class DomUtils {
+
+    private static final Log LOG = LogFactory.getLog(DomUtils.class);
+
+    /**
+     * Disabled default constructor.
+     * 
+     */
+    private DomUtils() {
+        // Empty.
+    }
+
+    /**
+     * Parses an XML document from a string.
+     * 
+     * @param aDocument
+     *            document.
+     * @return
+     */
+    public static Document read(String aDocument) throws XMLException {
+        ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
+        return read(is);
+    }
+
+    /**
+     * Parses an XML document from a stream.
+     * 
+     * @param aIs
+     *            Input stream.
+     * @return
+     */
+    public static Document read(InputStream aIs) throws XMLException {
+        try {
+            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
+                    .newDocumentBuilder();
+            return builder.parse(aIs);
+        }  catch (SAXException e) {
+            throw new XMLException(e.getMessage(), e);
+        } catch (IOException e) {
+            throw new XMLException(e.getMessage(), e);
+        } catch (ParserConfigurationException e) {
+            throw new XMLException(e.getMessage(), e);
+        } finally {
+            try {
+                aIs.close();
+            } catch (Exception e) {
+                LOG.warn("Error closing XML file", e);
+            }
+        }
+    }
+
+    /**
+     * Reads and validates a document against a schema.
+     * 
+     * @param aIs
+     *            Input stream.
+     * @param aSchema
+     *            Schema.
+     * @return Parsed and validated document.
+     */
+    public static Document readAndValidate(InputStream aIs, InputStream aSchema)
+            throws XMLException {
+
+        try {
+            final Schema schema = SchemaFactory.newInstance(
+                    XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
+                    new StreamSource(aSchema));
+
+            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+            factory.setValidating(true);
+            factory.setNamespaceAware(true);
+            factory.setSchema(schema);
+
+            return factory.newDocumentBuilder().parse(aIs);
+        } catch (SAXException e) {
+            throw new XMLException(e.getMessage(), e);
+        } catch (IOException e) {
+            throw new XMLException(e.getMessage(), e);
+        } catch (ParserConfigurationException e) {
+            throw new XMLException(e.getMessage(), e);
+        } finally {
+            try {
+                aSchema.close();
+            } catch (Exception e) {
+                LOG.warn("Error closing schema", e);
+            }
+            try {
+                aIs.close();
+            } catch (Exception e) {
+                LOG.warn("Error closing XML file", e);
+            }
+        }
+
+    }
+
+    /**
+     * Serializes an XML document to a stream.
+     * 
+     * @param aDocument
+     *            Document to serialize.
+     * @param aOs
+     *            Output stream.
+     */
+    public static void serialize(Document aDocument, OutputStream aOs)
+            throws IOException {
+        XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
+        serializer.serialize(aDocument);
+    }
+
+    /**
+     * Serializes an XML document.
+     * 
+     * @param aDocument
+     *            Document to serialize.
+     * @return Serialized document.
+     */
+    public static String serialize(Document aDocument) throws IOException {
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        serialize(aDocument, os);
+        return os.toString();
+    }
+
+    /**
+     * Converts a dom4j document into a w3c DOM document.
+     * 
+     * @param aDocument
+     *            Document to convert.
+     * @return W3C DOM document.
+     */
+    public static Document convert(org.dom4j.Document aDocument)
+            throws DocumentException {
+        return new DOMWriter().write(aDocument);
+    }
+
+    /**
+     * Converts a W3C DOM document into a dom4j document.
+     * 
+     * @param aDocument
+     *            Document to convert.
+     * @return Dom4j document.
+     */
+    public static org.dom4j.Document convert(Document aDocument) {
+        return new DOMReader().read(aDocument);
+    }
+
+    /**
+     * Removes duplicate attributes from a DOM tree.This is useful for
+     * postprocessing the output of JTidy as a workaround for a bug in JTidy.
+     * 
+     * @param aNode
+     *            Node to remove duplicate attributes from (recursively).
+     *            Attributes of the node itself are not dealt with. Only the
+     *            child nodes are dealt with.
+     */
+    public static void removeDuplicateAttributes(Node aNode) {
+        NodeList list = aNode.getChildNodes();
+        for (int i = 0; i < list.getLength(); i++) {
+            Node node = list.item(i);
+            if (node instanceof Element) {
+                removeDuplicateAttributes((Element) node);
+                removeDuplicateAttributes(node);
+            }
+        }
+    }
+
+    /**
+     * Removes duplicate attributes from an element.
+     * 
+     * @param aElement
+     *            Element.
+     */
+    private static void removeDuplicateAttributes(Element aElement) {
+        NamedNodeMap attributes = aElement.getAttributes();
+        Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
+        List<Attr> attlist = new ArrayList<Attr>();
+        for (int i = 0; i < attributes.getLength(); i++) {
+            Attr attribute = (Attr) attributes.item(i);
+            if (uniqueAttributes.containsKey(attribute.getNodeName())) {
+                LOG.info("Detected duplicate attribute (will be removed)'"
+                        + attribute.getNodeName() + "'");
+            }
+            uniqueAttributes.put(attribute.getNodeName(), attribute);
+            attlist.add(attribute);
+        }
+        // Remove all attributes from the element.
+        for (Attr att : attlist) {
+            aElement.removeAttributeNode(att);
+        }
+        // Add the unique attributes back to the element.
+        for (Attr att : uniqueAttributes.values()) {
+            aElement.setAttributeNode(att);
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/XMLException.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/XMLException.java
new file mode 100644 (file)
index 0000000..06363c4
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+/**
+ * Exception thrown in case of XML parsing problems.  
+ *
+ * @author Erik Brakkee
+ */
+public class XMLException extends Exception {
+
+    public XMLException(String aMsg) { 
+        super(aMsg); 
+    }
+    
+    public XMLException(String aMsg, Throwable aCause) { 
+        super(aMsg, aCause);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/XslTransformer.java b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/XslTransformer.java
new file mode 100644 (file)
index 0000000..fb3d305
--- /dev/null
@@ -0,0 +1,176 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.dom.DOMResult;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.w3c.dom.Document;
+import org.wamblee.io.FileResource;
+
+/**
+ * XSL transformer for simplified usage of XSL transformations.
+ *
+ * @author Erik Brakkee
+ */
+public class XslTransformer {
+
+    private TransformerFactory _factory;
+
+    /**
+     * Constructs the URL resolver.
+     * 
+     * @param aResolver
+     *            URI resolver to use.
+     */
+    public XslTransformer(URIResolver aResolver) {
+        _factory = TransformerFactory.newInstance();
+        _factory.setURIResolver(aResolver);
+    }
+
+    /**
+     * Constructs the XSLT processor.
+     * 
+     */
+    public XslTransformer() {
+        _factory = TransformerFactory.newInstance();
+    }
+
+    /**
+     * Resolves an XSLT based on URI. 
+     * @param aXslt XSLT to resolve, 
+     * @return Source for the XSLT
+     * @throws TransformerException In case the XSLT cannot be found. 
+     */
+    public Source resolve(String aXslt) throws TransformerException {
+        URIResolver resolver = _factory.getURIResolver();
+        if (resolver == null) {
+            if (new File(aXslt).canRead()) {
+                try {
+                    return new StreamSource(new FileResource(new File(aXslt))
+                            .getInputStream());
+                } catch (IOException e) {
+                    throw new TransformerException(e.getMessage(), e);
+                }
+            } else {
+                throw new TransformerException("Cannot read '" + aXslt + "'"); 
+            }
+        }
+        return resolver.resolve(aXslt, "");
+    }
+
+    /**
+     * Transforms a DOM document into another DOM document using a given XSLT
+     * transformation.
+     * 
+     * @param aDocument
+     *            Document to transform.
+     * @param aXslt
+     *            XSLT to use.
+     * @return Transformed document.
+     * @throws IOException
+     *             In case of problems reading resources.
+     * @throws TransformerException
+     *             In case transformation fails.
+     */
+    public Document transform(Document aDocument, Source aXslt)
+            throws IOException, TransformerException {
+        Source source = new DOMSource(aDocument);
+        DOMResult result = new DOMResult();
+        transform(source, result, aXslt);
+        return (Document) result.getNode();
+    }
+
+    /**
+     * Transforms a document using XSLT.
+     * 
+     * @param aDocument
+     *            Document to transform.
+     * @param aXslt
+     *            XSLT to use.
+     * @return Transformed document.
+     * @throws IOException
+     *             In case of problems reading resources.
+     * @throws TransformerException
+     *             In case transformation fails.
+     */
+    public Document transform(byte[] aDocument, Source aXslt)
+            throws IOException, TransformerException {
+        Source source = new StreamSource(new ByteArrayInputStream(aDocument));
+        DOMResult result = new DOMResult();
+        transform(source, result, aXslt);
+        return (Document) result.getNode();
+    }
+
+    /**
+     * Transforms a document to a text output. This supports XSLT
+     * transformations that result in text documents.
+     * 
+     * @param aDocument
+     *            Document to transform.
+     * @param aXslt
+     *            XSL transformation.
+     * @return Transformed document.
+     */
+    public String textTransform(byte[] aDocument, Source aXslt)
+            throws IOException, TransformerException {
+        Source source = new StreamSource(new ByteArrayInputStream(aDocument));
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        StreamResult result = new StreamResult(os);
+        transform(source, result, aXslt);
+        return new String(os.toByteArray());
+    }
+
+    /**
+     * Transforms a document using XSLT.
+     * 
+     * @param aSource
+     *            Document to transform.
+     * @param aResult
+     *            Result of the transformation.
+     * @param aXslt
+     *            XSLT to use.
+     * @throws IOException
+     *             In case of problems reading resources.
+     * @throws TransformerException
+     *             In case transformation fails.
+     */
+    public void transform(Source aSource, Result aResult, Source aXslt)
+            throws IOException, TransformerException {
+        try {
+            Transformer transformer = _factory.newTransformer(aXslt);
+            transformer.transform(aSource, aResult);
+        } catch (TransformerConfigurationException e) {
+            throw new TransformerException(
+                    "Configuration problem of XSLT transformation", e);
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/package.html b/tags/wamblee-utils-0.2.1/support/general/src/main/java/org/wamblee/xml/package.html
new file mode 100644 (file)
index 0000000..5d1c9e8
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides support utilities for XML processing. 
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/main/resources/log4j.properties b/tags/wamblee-utils-0.2.1/support/general/src/main/resources/log4j.properties
new file mode 100644 (file)
index 0000000..b953f9b
--- /dev/null
@@ -0,0 +1,56 @@
+
+############################################################################################
+# Default configuration file for log4j. 
+#
+# This properties file is used if no other configuration if log4j is done explicitly.
+############################################################################################
+
+
+# Root logger reports everything and uses the console appender
+log4j.rootLogger=ERROR, console
+
+# Log level for wamblee.org
+log4j.logger.org.wamblee=INFO
+log4j.logger.org.wamblee.usermgt.UserAdministrationImplTest=INFO
+log4j.logger.org.wamblee.security.authorization=ERROR
+log4j.logger.org.wamblee.cache=INFO
+log4j.logger.org.wamblee.crawler=DEBUG
+
+log4j.logger.org.springframework=ERROR
+log4j.logger.net.sf.ehcache=WARN
+
+# Default log level for hibernate
+log4j.logger.org.hibernate=ERROR
+log4j.logger.org.hibernate3=ERROR
+
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
+
+######################################################################################
+# Hibernate SQL logging, switch the log level to DEBUG to see the output. 
+######################################################################################
+
+log4j.logger.org.wamblee.test.SpringTestCase=ERROR, console
+log4j.additivity.org.wamblee.test.SpringTestCase=false
+
+# Logging for queries.
+log4j.logger.org.hibernate.SQL=ERROR, sql
+log4j.additivity.org.hibernate.SQL=false
+
+# Logging for query parameters and return values.  
+log4j.logger.org.hibernate.type=ERROR, sqltype
+log4j.additivity.org.hibernate.type=false
+
+# Appender for the queries
+log4j.appender.sql=org.apache.log4j.ConsoleAppender
+log4j.appender.sql.layout=org.apache.log4j.PatternLayout
+log4j.appender.sql.layout.ConversionPattern=%n%-4r [%t] SQL: %x - %m%n
+
+# Appender to show the actual parameters and return values of the queries. 
+log4j.appender.sqltype=org.apache.log4j.ConsoleAppender
+log4j.appender.sqltype.layout=org.apache.log4j.PatternLayout
+log4j.appender.sqltype.layout.ConversionPattern=%-4r [%t] SQL:     %x - %m%n
+
+
+
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java
new file mode 100644 (file)
index 0000000..da6e1be
--- /dev/null
@@ -0,0 +1,176 @@
+/*
+ * Copyright 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.wamblee.cache;
+
+import java.io.IOException;
+
+import junit.framework.TestCase;
+import net.sf.ehcache.CacheException;
+
+import org.wamblee.io.TestResource;
+import org.wamblee.test.TimingUtils;
+
+/**
+ * Cached object test. 
+ *
+ * @author Erik Brakkee
+ */
+public class CachedObjectTest extends TestCase {
+    
+    /**
+     * 
+     */
+    private static final String EHCACHE_CONFIG = "ehcache.xml";
+
+    private static final int OBJECT_KEY = 10; 
+    
+    private CachedObject.Computation<Integer,Integer> _computation;
+    private int _ncomputations; 
+    
+    /* (non-Javadoc)
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        _computation = new CachedObject.Computation<Integer,Integer>() { 
+            public Integer getObject(Integer aObjectKey) {
+                _ncomputations++;
+                return compute(aObjectKey);
+            };
+        };
+        _ncomputations = 0; 
+    }
+    
+    private int compute(int aValue) { 
+        return aValue + 10;
+    }
+    
+    private CachedObject<Integer, Integer> createCached(Cache<Integer,Integer> aCache) { 
+        return new CachedObject<Integer, Integer>(aCache, OBJECT_KEY, _computation);
+    }
+
+    /**
+     * Verifies that upon first use, the cached object uses the computation to 
+     * retrieve the object.  
+     *
+     */
+    public void testComputation() { 
+        CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer,Integer>());
+        int value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations); 
+    }
+    
+    public void testInvalidateCache() { 
+        CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer,Integer>());
+        int value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations);
+        cached.invalidate(); 
+        value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(2, _ncomputations);
+    }
+    
+    public void testBehaviorEhCache() throws CacheException, IOException {
+        Cache<Integer,Integer> cache = new EhCache<Integer,Integer>(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "test");
+        CachedObject<Integer, Integer> cached = createCached(cache);
+        
+        assertTrue( cache == cached.getCache());
+        int value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations);
+        // The value must still be cached. 
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations);
+        
+        // Cache expiry. 
+        TimingUtils.sleep(6000); 
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(2, _ncomputations);
+        
+        // Should still be cached now.
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(2, _ncomputations);
+        
+        // explicit invalidation.
+        cached.invalidate(); 
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(3, _ncomputations);
+        
+    }
+    
+    public void testBehaviorEhCacheDefault() throws CacheException, IOException {
+        Cache<Integer,Integer> cache = new EhCache<Integer,Integer>(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "undefined");
+        CachedObject<Integer, Integer> cached = createCached(cache);
+        
+        assertTrue( cache == cached.getCache());
+        int value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations);
+        // The value must still be cached. 
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations);
+        
+        // Cache expiry. 
+        TimingUtils.sleep(6000); 
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(2, _ncomputations);
+        
+        // Should still be cached now.
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(2, _ncomputations);
+        
+    }
+    
+    
+    public void testBehaviorForeverCache() { 
+        CachedObject<Integer, Integer> cached = createCached(new ForeverCache<Integer,Integer>());
+        int value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations); 
+        for (int ncomp = 2; ncomp <= 100; ncomp++) { 
+            value = cached.get(); 
+            assertEquals(compute(OBJECT_KEY), value);
+            assertEquals(1, _ncomputations);
+        }
+    }
+    
+    public void testBehaviorZeroCache() { 
+        CachedObject<Integer, Integer> cached = createCached(new ZeroCache<Integer,Integer>());
+        int value = cached.get();
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(1, _ncomputations); 
+        for (int ncomp = 2; ncomp <= 100; ncomp++) { 
+            value = cached.get(); 
+            assertEquals(compute(OBJECT_KEY), value);
+            assertEquals(ncomp, _ncomputations);
+        }
+        cached.invalidate(); 
+        value = cached.get(); 
+        assertEquals(compute(OBJECT_KEY), value);
+        assertEquals(101, _ncomputations);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java
new file mode 100644 (file)
index 0000000..1e56eac
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 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.wamblee.collections;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.wamblee.conditions.Condition;
+import org.wamblee.test.AssertionUtils;
+
+import junit.framework.TestCase;
+
+public class CollectionFilterTest extends TestCase {
+       
+       public void testFilter() { 
+               List<String> list = Arrays.asList(new String[] { "x", "y", "z", "y" }); 
+               List<String> result = new ArrayList<String>();
+               CollectionFilter.filter(list, result, 
+                               new Condition<String>() { 
+                       @Override
+                       public boolean matches(String aObject) {
+                               return aObject.equals("y");
+                       }
+               });
+               AssertionUtils.assertEquals(new String[] { "y", "y" }, result.toArray());
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java
new file mode 100644 (file)
index 0000000..39cec11
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright 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.wamblee.concurrency;
+
+import org.wamblee.test.EventTracker;
+import org.wamblee.test.TimingUtils;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for the JVMLock.
+ *
+ * @author Erik Brakkee
+ */
+public abstract class AbstractLockTestCase extends TestCase {
+
+    protected static final int SLEEP_TIME = 1000;
+
+    protected static final String STARTED = "started";
+
+    protected static final String ACQUIRED = "acquired";
+
+    protected static final String RELEASED = "released";
+
+    private EventTracker<String> _tracker;
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        _tracker = new EventTracker<String>();
+    }
+    
+    protected EventTracker<String> getTracker() { 
+        return _tracker;
+    }
+
+    /**
+     * Must be implemented to generate the events 
+     * {@link #STARTED}, {@link #ACQUIRED}, and {@link #RELEASED} in 
+     * that order. The lock should be acquired for
+     * the time specified by {@link #SLEEP_TIME}.
+     * @return Thread which does the work. 
+     */
+    protected abstract Thread runThread();
+
+    /**
+     * Tests the operation of the lock.
+     */
+    public void testLock() throws InterruptedException {
+        Thread t1 = runThread();
+        Thread t2 = runThread();
+        TimingUtils.sleep(SLEEP_TIME / 10); // give threads a chance to start
+        // up.
+        assertEquals(2, _tracker.getEventCount(STARTED)); // both threads
+        // should have
+        // started.
+        assertEquals(1, _tracker.getEventCount(ACQUIRED)); // one thread has
+                                                            // acquired the
+                                                            // lock.
+        TimingUtils.sleep(SLEEP_TIME);
+        assertEquals(2, _tracker.getEventCount(ACQUIRED)); // now the other
+                                                            // thread could also
+                                                            // acquire the lock
+        assertEquals(1, _tracker.getEventCount(RELEASED)); // and the first
+                                                            // thread has
+                                                            // released it.
+        TimingUtils.sleep(SLEEP_TIME);
+        assertEquals(2, _tracker.getEventCount(RELEASED)); // both threads
+                                                            // should be
+                                                            // finished.
+        t1.join();
+        t2.join();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java
new file mode 100644 (file)
index 0000000..e14ca9b
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.concurrency;
+
+import org.wamblee.test.TimingUtils;
+
+/**
+ * Tests for the JVMLock.
+ *
+ * @author Erik Brakkee
+ */
+public class JvmLockTest extends AbstractLockTestCase {
+
+    private JvmLock _lock;
+    
+    /*
+     * (non-Javadoc)
+     * 
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        _lock = new JvmLock();
+    }
+
+    protected Thread runThread() {
+        Thread t = new Thread(new Runnable() {
+            public void run() {
+                getTracker().eventOccurred(STARTED);
+                _lock.acquire();
+                getTracker().eventOccurred(ACQUIRED);
+                TimingUtils.sleep(SLEEP_TIME);
+                _lock.release();
+                getTracker().eventOccurred(RELEASED);
+            };
+        });
+        t.start();
+        return t;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java
new file mode 100644 (file)
index 0000000..40302f7
--- /dev/null
@@ -0,0 +1,509 @@
+/*
+ * Copyright 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.wamblee.concurrency;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+
+/**
+ * Testing the read-write lock class. Note: in case of problems, test cases
+ * could hang.
+ *
+ * @see ReadWriteLock
+ */
+public class ReadWriteLockTest extends TestCase {
+    /**
+     * 
+     */
+    private static final int HALF_SECOND = 500;
+    /**
+     * 
+     */
+    private static final int ONE_SECOND = 1000;
+    /**
+     * 
+     */
+    private static final int TWO_SECONDS = 2000;
+    private ReadWriteLock _lock;
+    private int                   _nReaders;
+    private int                   _nWriters;
+
+    /**
+     * Constructor for ReadWriteLockTest.
+     *
+     * @param aName
+     */
+    public ReadWriteLockTest(String aName) {
+        super(aName);
+    }
+
+    private synchronized int getReaderCount() {
+        return _nReaders;
+    }
+
+    private synchronized int getWriterCount() {
+        return _nWriters;
+    }
+
+    synchronized void incrementReaderCount() {
+        _nReaders++;
+    }
+
+    synchronized void incrementWriterCount() {
+        _nWriters++;
+    }
+
+    synchronized void decrementReaderCount() {
+        _nReaders--;
+    }
+
+    synchronized void decrementWriterCount() {
+        _nWriters--;
+    }
+
+    /*
+     * @see TestCase#setUp()
+     */
+    protected void setUp() throws Exception {
+        super.setUp();
+        _lock = new ReadWriteLock();
+    }
+
+    /*
+     * @see TestCase#tearDown()
+     */
+    protected void tearDown() throws Exception {
+        _lock = null;
+        super.tearDown();
+    }
+
+    /**
+     * Acquire and release a read lock.
+     */
+    public void testRead() {
+        _lock.acquireRead();
+        _lock.releaseRead();
+    }
+
+    /**
+     * Acquire and release a write lock.
+     */
+    public void testWrite() {
+        _lock.acquireWrite();
+        _lock.releaseWrite();
+    }
+
+    /**
+     * Verify concurrent access by multiple readers is possible.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testMultipleReaders() throws InterruptedException {
+        Runnable runnable = new ReadLocker(_lock, this, TWO_SECONDS);
+
+        Thread   t1 = new Thread(runnable);
+        t1.start();
+
+        Thread t2 = new Thread(runnable);
+        t2.start();
+        Thread.sleep(ONE_SECOND);
+        assertTrue("Not enough readers!", getReaderCount() == 2);
+        t1.join();
+        t2.join();
+    }
+
+    /**
+     * Verify that only one writer at a time can acquire the write lock.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testSingleWriter() throws InterruptedException {
+        WriteLocker writer = new WriteLocker(_lock, this, ONE_SECOND);
+        Thread      t1 = new Thread(writer);
+        Thread      t2 = new Thread(writer);
+
+        t1.start();
+        t2.start();
+        Thread.sleep(HALF_SECOND);
+        assertTrue("Wrong writer count: " + getWriterCount(),
+            getWriterCount() == 1);
+        t1.join();
+        t2.join();
+    }
+
+    /**
+     * Verify that multiple writers cannot acquire the write lock concurrently.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testMultipleWriters() throws InterruptedException {
+        WriteLocker writer1 = new WriteLocker(_lock, this, HALF_SECOND + ONE_SECOND);
+        WriteLocker writer2 = new WriteLocker(_lock, this, ONE_SECOND);
+        Thread      t1      = new Thread(writer1);
+        Thread      t2      = new Thread(writer2);
+
+        t1.start();
+        Thread.sleep(HALF_SECOND);
+        assertTrue(getWriterCount() == 1);
+        t2.start();
+        Thread.sleep(HALF_SECOND);
+        assertTrue(getWriterCount() == 1); // first writer still
+
+        // has the lock.
+        Thread.sleep(ONE_SECOND);
+
+        // at t = 2, the second writer still must have
+        // a lock. 
+        assertTrue(getWriterCount() == 1);
+        t1.join();
+        t2.join();
+    }
+
+    /**
+     * Verify that after the first reader acquires a lock,  a subsequent writer
+     * can only acquire the lock after the reader has released it.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testReadWrite1() throws InterruptedException {
+        ReadLocker  readLocker  = new ReadLocker(_lock, this, TWO_SECONDS);
+        Thread      t1          = new Thread(readLocker);
+        WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS);
+        Thread      t2          = new Thread(writeLocker);
+
+        t1.start(); // acquire read lock
+        Thread.sleep(HALF_SECOND);
+        assertTrue(getReaderCount() == 1);
+        t2.start();
+        Thread.sleep(HALF_SECOND);
+
+        // 1 second underway, reader still holding the
+        //   lock so write lock cannot be acquired.
+        assertTrue(getReaderCount() == 1);
+        assertTrue(getWriterCount() == 0);
+        Thread.sleep(ONE_SECOND + HALF_SECOND);
+
+        // 2.5 seconds underway, read lock released and 
+        // write lock must be acquired. 
+        assertTrue("Wrong no. of readers: " + getReaderCount(),
+            getReaderCount() == 0);
+        assertTrue(getWriterCount() == 1);
+        t1.join();
+        t2.join();
+    }
+
+    /**
+     * Verify that when multiple readers have acquired a read lock, the writer
+     * can only acquire the lock after all readers have released it.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testReadWrite2() throws InterruptedException {
+        ReadLocker  readLocker1 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND);
+        ReadLocker  readLocker2 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND);
+        Thread      t1          = new Thread(readLocker1);
+        Thread      t2          = new Thread(readLocker2);
+        WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS);
+        Thread      t3          = new Thread(writeLocker);
+
+        t1.start(); // acquire read lock [0, 2.5]
+        Thread.sleep(ONE_SECOND);
+        // t = 1
+        assertTrue(getReaderCount() == 1);
+        t2.start(); // acquire read lock [1, 3.5]
+        Thread.sleep(HALF_SECOND);
+        // t = 1.5
+        assertTrue(getReaderCount() == 2);
+        t3.start(); // write lock 
+        Thread.sleep(HALF_SECOND);
+
+        // 2 seconds, 
+        assertTrue(getReaderCount() == 2);
+        assertTrue(getWriterCount() == 0);
+        Thread.sleep(ONE_SECOND);
+
+        // 3 seconds underway, first read lock must
+        // have been released.
+        assertTrue(getReaderCount() == 1);
+        assertTrue(getWriterCount() == 0);
+        Thread.sleep(ONE_SECOND);
+
+        // 4 seconds underway, write lock must have 
+        // been acquired. 
+        assertTrue(getReaderCount() == 0);
+        assertTrue(getWriterCount() == 1);
+
+        t1.join();
+        t2.join();
+        t3.join();
+    }
+
+    /**
+     * Verify that after a writer acquires a lock,  a subsequent reader can
+     * only acquire the lock after the writer has released it.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testReadWrite3() throws InterruptedException {
+        ReadLocker  readLocker  = new ReadLocker(_lock, this, TWO_SECONDS);
+        Thread      t1          = new Thread(readLocker);
+        WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS);
+        Thread      t2          = new Thread(writeLocker);
+
+        t2.start(); // acquire write lock
+        Thread.sleep(HALF_SECOND);
+        assertTrue(getWriterCount() == 1);
+        t1.start();
+        Thread.sleep(HALF_SECOND);
+
+        // 1 second underway, writer still holding the
+        //   lock so read lock cannot be acquired.
+        assertTrue(getWriterCount() == 1);
+        assertTrue(getReaderCount() == 0);
+        Thread.sleep(ONE_SECOND + HALF_SECOND);
+
+        // 2.5 seconds underway, write lock released and 
+        // read lock must be acquired. 
+        assertTrue("Wrong no. of writers: " + getReaderCount(),
+            getWriterCount() == 0);
+        assertTrue(getReaderCount() == 1);
+        t1.join();
+        t2.join();
+    }
+
+    /*
+     * The following test cases are for testing whether or not
+     * the read write lock checks the locking correctly.
+     * Strictly speaking, these checks wouldn't be necessary
+     * because it involves the contract of the ReadWriteLock which
+     * must be obeyed by users of the ReadWriteLock. Nevertheless,
+     * this is tested anyway to be absolutely sure.
+     */
+
+    /**
+     * Acquire a read lock from one thread, release it from another. Verify
+     * that a RuntimeException is thrown.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testReleaseReadFromWrongThread() throws InterruptedException {
+        Thread t1 = null;
+
+        try {
+            t1 = new Thread(new Runnable() {
+                        public void run() {
+                            ReadWriteLockTest.this._lock.acquireRead();
+                        }
+                    });
+            t1.start();
+            Thread.sleep(ONE_SECOND); // wait until thread is started
+            _lock.releaseRead(); // release lock from wrong thread.
+        } catch (RuntimeException e) {
+            return; // ok
+        } finally {
+            t1.join();
+        }
+
+        fail();
+    }
+
+    /**
+     * Acquire a write lock from one thread, release it from another. Verify
+     * that a RuntimeException is thrown.
+     *
+     * @throws InterruptedException May not occur.
+     */
+    public void testReleaseWriteFromWrongThread() throws InterruptedException {
+        Thread t1 = null;
+
+        try {
+            t1 = new Thread(new Runnable() {
+                        public void run() {
+                            ReadWriteLockTest.this._lock.acquireWrite();
+                        }
+                    });
+            t1.start();
+            Thread.sleep(ONE_SECOND); // wait until thread is started
+            _lock.releaseWrite(); // release lock from wrong thread.
+        } catch (RuntimeException e) {
+            return; // ok
+        } finally {
+            t1.join();
+        }
+
+        fail();
+    }
+
+    /**
+     * Try to acquire a read lock multiple times. Verify that a
+     * RuntimeException is thrown.
+     */
+    public void testAcquireReadTwice() {
+        try {
+            _lock.acquireRead();
+            _lock.acquireRead();
+        } catch (RuntimeException e) {
+            // ok
+            return;
+        }
+
+        fail();
+    }
+
+    /**
+     * Try to acquire a write lock multiple times. Verify that a
+     * RuntimeException is thrown.
+     */
+    public void testAcquireWriteTwice() {
+        try {
+            _lock.acquireWrite();
+            _lock.acquireWrite();
+        } catch (RuntimeException e) {
+            return; // ok
+        }
+
+        fail();
+    }
+
+    /**
+     * Acquire the lock for reading and directly afterwards acquire it for
+     * writing. Verify that a RuntimeException is thrown.
+     */
+    public void testAcquireReadFollowedByWrite() {
+        try {
+            _lock.acquireRead();
+            _lock.acquireWrite();
+        } catch (RuntimeException e) {
+            return; // ok
+        }
+
+        fail();
+    }
+
+    /**
+     * Acquire the lock for writing and directly afterwards acquire it for
+     * reading. Verify that a RuntimeException is thrown.
+     */
+    public void testAcquireWriteFollowedByRead() {
+        try {
+            _lock.acquireWrite();
+            _lock.acquireRead();
+        } catch (RuntimeException e) {
+            return; // ok
+        }
+
+        fail();
+    }
+
+    /**
+     * Acquire a read lock and release it as a write lock. Verify that a
+     * RuntimeException is thrown.
+     */
+    public void testAcquireReadFollowedByReleaseaWrite() {
+        try {
+            _lock.acquireRead();
+            _lock.releaseWrite();
+        } catch (RuntimeException e) {
+            return; // ok
+        }
+
+        fail();
+    }
+
+    /**
+     * Acquire a write lock and release it as a read lock. Verify that a
+     * RuntimeException is thrown.
+     */
+    public void testAcquireWriteFollowedByReleaseRead() {
+        try {
+            _lock.acquireWrite();
+            _lock.releaseRead();
+        } catch (RuntimeException e) {
+            return; // ok
+        }
+
+        fail();
+    }
+}
+
+
+/**
+ * ReadLocker acquires a read lock and performs a callback when  the lock as
+ * been acquired, sleeps for a designated amount of time, releases the read
+ * lock, and performs a callback after the lock has been released.
+ */
+class ReadLocker implements Runnable {
+    private ReadWriteLock     _lock;
+    private ReadWriteLockTest _lockTest;
+    private int               _sleepTime;
+
+    public ReadLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest,
+        int aSleepTime) {
+        _lock          = aLock;
+        _lockTest      = aLockTest;
+        _sleepTime     = aSleepTime;
+    }
+
+    public void run() {
+        _lock.acquireRead();
+        _lockTest.incrementReaderCount();
+
+        try {
+            Thread.sleep(_sleepTime);
+        } catch (InterruptedException e) {
+            Assert.fail("ReadLocker thread was interrupted."
+                + Thread.currentThread());
+        }
+
+        _lock.releaseRead();
+        _lockTest.decrementReaderCount();
+    }
+}
+
+
+/**
+ * WriteLocker acquires a write lock and performs a callback when  the lock as
+ * been acquired, sleeps for a designated amount of time, releases the write
+ * lock, and performs a callback after the lock has been released.
+ */
+class WriteLocker implements Runnable {
+    private ReadWriteLock     _lock;
+    private ReadWriteLockTest _lockTest;
+    private int               _sleepTime;
+
+    public WriteLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest,
+        int aSleepTime) {
+        _lock          = aLock;
+        _lockTest      = aLockTest;
+        _sleepTime     = aSleepTime;
+    }
+
+    public void run() {
+        _lock.acquireWrite();
+        _lockTest.incrementWriterCount();
+
+        try {
+            Thread.sleep(_sleepTime);
+        } catch (InterruptedException e) {
+            Assert.fail("WriteLocker thread was interrupted: "
+                + Thread.currentThread());
+        }
+
+        _lock.releaseWrite();
+        _lockTest.decrementWriterCount();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java
new file mode 100644 (file)
index 0000000..81c4e4e
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the Or Condition.  
+ *
+ * @author Erik Brakkee
+ */
+public class AndConditionTest extends TestCase {
+    
+    public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { 
+        AndCondition<Integer> and = new AndCondition<Integer>(new FixedCondition<Integer>(aFirst), 
+                new FixedCondition<Integer>(aSecond)); 
+        assertEquals(aResult, and.matches(0));
+    }
+    
+    public void checkResult(boolean[] aValues, boolean aResult) { 
+        List<Condition<Integer>> conditions = new ArrayList<Condition<Integer>>();
+        for (boolean value: aValues) { 
+            conditions.add(new FixedCondition<Integer>(value)); 
+        }
+        AndCondition<Integer> and = new AndCondition<Integer>(conditions);
+        assertEquals(aResult, and.matches(new Integer(0)));
+    }
+
+    /**
+     * Checks all combinations of two conditions. 
+     *
+     */
+    public void testTwoConditions() { 
+        checkResult(false, false, false);
+        checkResult(true, false, false);
+        checkResult(false, true, false); 
+        checkResult(true, true, true);
+    }
+    
+    public void testMultipleConditions() { 
+        checkResult(new boolean[]{ false, false, false} , false);
+        checkResult(new boolean[]{ true, false, false }, false); 
+        checkResult(new boolean[]{ false, true, false }, false); 
+        checkResult(new boolean[]{ false, false, true }, false); 
+        checkResult(new boolean[]{ true, true, true }, true); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java
new file mode 100644 (file)
index 0000000..bdb9589
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+/**
+ * Test condition object.  
+ *
+ * @author Erik Brakkee
+ */
+public class GreaterThanCondition implements Condition<Integer> {
+    
+    private int _value; 
+    
+    public GreaterThanCondition(int aValue) { 
+        _value = aValue; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.conditions.Condition#matches(T)
+     */
+    public boolean matches(Integer aObject) {
+        return aObject > _value; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java
new file mode 100644 (file)
index 0000000..06ab192
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+/**
+ * Test condition object.  
+ *
+ * @author Erik Brakkee
+ */
+public class LessThanCondition implements Condition<Integer> {
+    
+    private int _value; 
+    
+    public LessThanCondition(int aValue) { 
+        _value = aValue; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.wamblee.conditions.Condition#matches(T)
+     */
+    public boolean matches(Integer aObject) {
+        return aObject < _value; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java
new file mode 100644 (file)
index 0000000..c3f7df1
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the Or Condition.  
+ *
+ * @author Erik Brakkee
+ */
+public class OrConditionTest extends TestCase {
+    
+    public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { 
+        OrCondition<Integer> or = new OrCondition<Integer>(new FixedCondition<Integer>(aFirst), 
+                new FixedCondition<Integer>(aSecond)); 
+        assertEquals(aResult, or.matches(0));
+    }
+    
+    public void checkResult(boolean[] aValues, boolean aResult) { 
+        List<Condition<Integer>> conditions = new ArrayList<Condition<Integer>>();
+        for (boolean value: aValues) { 
+            conditions.add(new FixedCondition<Integer>(value)); 
+        }
+        OrCondition<Integer> or = new OrCondition<Integer>(conditions);
+        assertEquals(aResult, or.matches(new Integer(0)));
+    }
+
+    /**
+     * Checks all combinations of two conditions. 
+     *
+     */
+    public void testTwoConditions() { 
+        checkResult(false, false, false);
+        checkResult(true, false, true);
+        checkResult(false, true, true); 
+        checkResult(true, true, true);
+    }
+    
+    public void testMultipleConditions() { 
+        checkResult(new boolean[]{ false, false, false} , false);
+        checkResult(new boolean[]{ true, false, false }, true); 
+        checkResult(new boolean[]{ false, true, false }, true); 
+        checkResult(new boolean[]{ false, false, true }, true); 
+        checkResult(new boolean[]{ true, true, true }, true); 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java
new file mode 100644 (file)
index 0000000..9f494fb
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests {@link org.wamblee.conditions.PropertyRegexCondition}. 
+ *
+ * @author Erik Brakkee
+ */
+public class PropertyRegexConditionTest extends TestCase {
+  
+    private boolean match(String aProperty, String aRegex, boolean aToLower, TestBean aBean) { 
+        PropertyRegexCondition<TestBean> condition = new PropertyRegexCondition<TestBean>(aProperty, aRegex, aToLower );
+        return condition.matches(aBean);
+    }
+    
+    private void checkMatch(String aProperty, String aRegex, boolean aToLower, TestBean aBean, boolean aResult) { 
+        assertEquals( aResult, match(aProperty, aRegex, aToLower, aBean)); 
+    }
+  
+    /**
+     * Verifies correct matching behavior for several cases. 
+     *
+     */
+    public void testMatchProperty() {
+        TestBean bean = new TestBean("Hallo"); 
+        checkMatch("value", "Hallo", false, bean, true); 
+        checkMatch("value", "all", false, bean, false);
+        checkMatch("value", ".a.*o", false, bean, true);
+        checkMatch("value", "hallo", false, bean, false); // no match when not converting to lower case.
+        checkMatch("value", "hallo", true, bean, true); // match!
+    }
+    
+    /**
+     * Uses property regex condition for non-existing property. 
+     * Verifies that a runtime exception is thrown. 
+     *
+     */
+    public void testWrongProperty() { 
+        TestBean bean = new TestBean("Hallo");
+        try { 
+           match("bla", ".*", false, bean);       
+        } catch (RuntimeException e) { 
+           return; // ok
+        }
+        fail();
+    }
+    
+    /**
+     * Applies condition to a private property. Verifies that a runtime 
+     * exception is thrown. 
+     *
+     */
+    public void testPrivateProperty() { 
+        TestBean bean = new TestBean("Hallo");
+        try { 
+           match("privateValue", ".*", false, bean);       
+        } catch (RuntimeException e) { 
+           return; // ok
+        }
+        fail();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/TestBean.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/conditions/TestBean.java
new file mode 100644 (file)
index 0000000..7bcd6d2
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 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.wamblee.conditions;
+
+/**
+ * 
+ *
+ * @author Erik Brakkee
+ */
+public class TestBean {
+
+    private String _value; 
+    
+    public TestBean(String aValue) { 
+        _value = aValue; 
+    }
+    
+    public String getValue() { 
+        return _value; 
+    }
+    
+    private String getPrivateValue() { 
+        return _value; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java
new file mode 100644 (file)
index 0000000..2c9f898
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright 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.wamblee.general;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the bean kernel. The lookup of the bean factory itself can be tested
+ * only partially. Using a global property file for all test cases would tie all
+ * test cases together therefore no global property file is used.
+ *
+ * @author Erik Brakkee
+ */
+public class BeanKernelTest extends TestCase {
+
+    /**
+     * Loads the bean factory based on a property file configuration. Verifies
+     * the correct bean factory is loaded.
+     * 
+     */
+    public void testLoadBeanFactoryFromProperties() {
+        BeanFactory factory = BeanKernel
+                .lookupBeanFactory("org/wamblee/general/beankernel.properties");
+        assertTrue(factory instanceof TestBeanFactory);
+    }
+
+    /**
+     * Loads the bean factory based on a non-existing property file. 
+     * Verifies that BeanFactoryException is thrown. 
+     * 
+     */
+    public void testNonExistentPropertyFile() {
+        try {
+            BeanKernel
+                    .lookupBeanFactory("org/wamblee/general/beankernel-nonexistent.properties");
+        } catch (BeanFactoryException e) {
+            return; // ok
+        }
+        fail();
+    }
+    
+    /**
+     * Loads the bean factory based on a property file with a non-existing
+     * bean factory defined in it.  
+     * Verifies that BeanFactoryException is thrown. 
+     * 
+     */
+    public void testNonExistentBeanFactory() {
+        try {
+            BeanKernel
+                    .lookupBeanFactory("org/wamblee/general/beankernel-wrong.properties");
+        } catch (BeanFactoryException e) {
+            return; // ok
+        }
+        fail();
+    }
+    
+
+    /**
+     * Retrieves a bean factory throug the bean kernel. Verifies that beans can
+     * be retrieved.
+     * 
+     */
+    public void testRetrieveFactory() {
+        BeanKernel.overrideBeanFactory(new TestBeanFactory()); // bypass
+                                                                // default
+                                                                // property
+                                                                // lookup
+        BeanFactory factory = BeanKernel.getBeanFactory();
+        assertNotNull(factory);
+        assertEquals("hello", factory.find(String.class));
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/PairTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/PairTest.java
new file mode 100644 (file)
index 0000000..dcb6f61
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 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.wamblee.general;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the pair class. 
+ */
+public class PairTest extends TestCase {
+
+    public void testPair() { 
+        Pair<Integer, String> pair = new Pair<Integer, String>(10, "hello"); 
+        assertEquals(new Integer(10), pair.getFirst());
+        assertEquals("hello", pair.getSecond());
+        
+        Pair<Integer, String> pair2 = new Pair<Integer, String>(pair);
+        assertEquals(new Integer(10), pair2.getFirst());
+        assertEquals("hello", pair2.getSecond());
+        
+        
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java
new file mode 100644 (file)
index 0000000..6198e9b
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 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.wamblee.general;
+
+public class TestBeanFactory implements BeanFactory {
+
+       @Override
+       public Object find(String aId) {
+               return null;
+       }
+
+       @Override
+       public <T> T find(Class<T> aClass) {
+               if ( aClass.equals(String.class)) { 
+                       return (T)"hello";
+               }
+               return null; 
+       }
+
+       @Override
+       public <T> T find(String aId, Class<T> aClass) {
+               return null;
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java
new file mode 100644 (file)
index 0000000..70b05ab
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for the classpath resource.
+ */
+public class ClassPathResourceTest extends TestCase {
+
+    /**
+     * Loads an existing resource from the class path. Verifies it is found.
+     * 
+     */
+    public void testResourceFound() throws IOException {
+        ClassPathResource resource = new ClassPathResource(
+                "org/wamblee/io/myresource.txt");
+        InputStream is = resource.getInputStream();
+        String data = FileSystemUtils.read(is);
+        assertEquals("This is my resource", data);
+    }
+
+    /**
+     * Loads a non-existing resource from the class path. Verifies that an IO
+     * exception is thrown.
+     * 
+     */
+    public void testResourceNotFound() {
+        try {
+            ClassPathResource resource = new ClassPathResource(
+                    "org/wamblee/io/myresource-nonexistent.txt");
+            InputStream is = resource.getInputStream();
+        } catch (IOException e) {
+            return; // ok
+        }
+        fail();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java
new file mode 100644 (file)
index 0000000..12db916
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import static org.mockito.Mockito.*;
+import junit.framework.TestCase;
+
+import org.apache.oro.io.AwkFilenameFilter;
+
+public class DirectoryMonitorTest extends TestCase {
+
+       private static final String REGEX = "^.*\\.txt$";
+       private static final String FILE1 = "file1.txt";
+
+       private TestData _data;
+       private DirectoryMonitor.Listener _listener;
+
+       private DirectoryMonitor _monitor;
+
+       @Override
+       protected void setUp() throws Exception {
+               super.setUp();
+               _data = new TestData(this);
+               _data.clean();
+               _listener = mock(DirectoryMonitor.Listener.class);
+               _monitor = new DirectoryMonitor(_data.getRoot(), new AwkFilenameFilter(
+                               REGEX), _listener);
+       }
+
+       public void testEmptyDir() {
+               // Nothing is expected to be called.
+               for (int i = 0; i < 10; i++) {
+                       _monitor.poll();
+                       verifyNoMoreInteractions(_listener);
+               }
+       }
+
+       public void testFileCreated() {
+               _data.createFile(FILE1, "hello");
+               _monitor.poll();
+               verify(_listener).fileCreated(_data.getFile(FILE1));
+       }
+
+       public void testFileDeleted() {
+               _data.createFile(FILE1, "hello");
+               _monitor.poll();
+               reset(_listener);
+
+               _data.deleteFile(FILE1);
+               _monitor.poll();
+
+               verify(_listener).fileDeleted(_data.getFile(FILE1));
+               verifyNoMoreInteractions(_listener);
+       }
+
+       public void testFileChanged() throws InterruptedException {
+               _data.createFile(FILE1, "hello");
+               _monitor.poll();
+               reset(_listener);
+
+               Thread.sleep(2000);
+               _data.deleteFile(FILE1);
+               _data.createFile(FILE1, "bla");
+
+               _monitor.poll();
+               verify(_listener).fileChanged(_data.getFile(FILE1));
+               verifyNoMoreInteractions(_listener);
+       }
+
+       public void testFileFilterIsUsed() {
+               _monitor.poll();
+
+               _data.createFile("file.xml", "hello");
+               _monitor.poll();
+               verifyNoMoreInteractions(_listener);
+       }
+
+       public void testDirectoryIsIgnored() {
+               _monitor.poll();
+               _data.createDir(FILE1);
+               _monitor.poll();
+               verifyNoMoreInteractions(_listener);
+       }
+
+       public void testExceptionsWIllLeadToRepeatedNotifications() { 
+               _monitor.poll();
+               _data.createFile(FILE1, "hello");
+               
+               stubVoid(_listener).toThrow(new RuntimeException()).on().
+                fileCreated(_data.getFile(FILE1));
+               
+               try { 
+                   _monitor.poll();
+               } catch (RuntimeException e) { 
+                       reset(_listener); 
+                       
+                       // polling again should lead to the same filecreated call.
+                       // this time no exception is thrown.
+                       
+                       _monitor.poll();
+                       verify(_listener).fileCreated(_data.getFile(FILE1));
+                       verifyNoMoreInteractions(_listener);
+                       return; 
+               }
+               fail(); // should not get here.
+               
+       
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java
new file mode 100644 (file)
index 0000000..4f301cf
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.File;
+
+import org.apache.oro.io.AwkFilenameFilter;
+
+/**
+ * 
+ *
+ * @author Erik Brakkee
+ */
+public class DirectoryMonitorTestProgram {
+    
+    public static void main(String[] aArgs) throws Exception { 
+        
+        DirectoryMonitor monitor = new DirectoryMonitor(new File("."), 
+                new AwkFilenameFilter(".*\\.txt"), new DirectoryMonitor.Listener() { 
+            public void fileChanged(File aFile) {
+                System.out.println("changed " + aFile);            
+            }
+            public void fileCreated(File aFile) {
+                System.out.println("created " + aFile);   
+            }
+            public void fileDeleted(File aFile) {
+                System.out.println("deleted " + aFile);   
+            }
+        });
+        
+        for (;;) { 
+            monitor.poll();
+            Thread.sleep(1000);
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/FileResourceTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/FileResourceTest.java
new file mode 100644 (file)
index 0000000..c1564f0
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the file resource. 
+ *
+ * @author Erik Brakkee
+ */
+public class FileResourceTest extends TestCase {
+
+    /**
+     * Loads an existing resource. Verifies it is found.
+     * 
+     */
+    public void testResourceFound() throws IOException {
+        FileResource resource = new FileResource( new File(
+                FileSystemUtils.getTestInputDir(FileResourceTest.class), 
+                "myresource.txt"));
+        InputStream is = resource.getInputStream();
+        String data = FileSystemUtils.read(is);
+        assertEquals("This is my resource", data);
+    }
+
+    /**
+     * Loads a non-existing resource. Verifies that an IO
+     * exception is thrown.
+     * 
+     */
+    public void testResourceNotFound() {
+        try {
+            FileResource resource = new FileResource( new File(
+                    FileSystemUtils.getTestInputDir(FileResourceTest.class), 
+                    "myresource-nonexistent.txt"));
+            InputStream is = resource.getInputStream();
+        } catch (IOException e) {
+            return; // ok
+        }
+        fail();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java
new file mode 100644 (file)
index 0000000..ad3b4e2
--- /dev/null
@@ -0,0 +1,369 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.CodeSource;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * File system utilities.
+ * 
+ * @author Erik Brakkee
+ */
+public final class FileSystemUtils {
+
+       private static final Log LOG = LogFactory.getLog(FileSystemUtils.class);
+
+       /**
+        * Test output directory relative to the sub project.
+        */
+       private static final String TEST_OUTPUT_DIR = "../target/testoutput";
+
+       /**
+        * Test input directory relative to the sub project.
+        */
+       private static final String TEST_INPUT_DIR = "../src/test/resources";
+
+       /*
+        * Disabled.
+        * 
+        */
+       private FileSystemUtils() {
+               // Empty
+       }
+
+       /**
+        * Deletes a directory recursively. The test case will fail if the directory
+        * does not exist or if deletion fails.
+        * 
+        * @param aDir
+        *            Directory to delete.
+        */
+       public static void deleteDirRecursively(String aDir) {
+               deleteDirRecursively(new File(aDir));
+       }
+
+       /**
+        * Deletes a directory recursively. See {@link #deleteDirRecursively}.
+        * 
+        * @param aDir
+        *            Directory.
+        */
+       public static void deleteDirRecursively(File aDir) {
+               TestCase.assertTrue(aDir.isDirectory());
+
+               for (File file : aDir.listFiles()) {
+                       if (file.isDirectory()) {
+                               deleteDirRecursively(file);
+                       } else {
+                               delete(file);
+                       }
+               }
+
+               delete(aDir);
+       }
+
+       /**
+        * Deletes a file or directory. The test case will fail if the file or
+        * directory does not exist or if deletion fails. Deletion of a non-empty
+        * directory will always fail.
+        * 
+        * @param aFile
+        *            File or directory to delete.
+        */
+       public static void delete(File aFile) {
+               TestCase.assertTrue(aFile.delete());
+       }
+
+       /**
+        * Gets a path relative to a sub project. This utility should be used to
+        * easily access file paths within a subproject without requiring any
+        * specific Eclipse configuration.
+        * 
+        * @param aRelativePath
+        *            Relative path.
+        * @param aTestClass
+        *            Test class.
+        */
+       public static File getPath(String aRelativePath, Class aTestClass) {
+               CodeSource source = aTestClass.getProtectionDomain().getCodeSource();
+               if (source == null) {
+                       LOG.warn("Could not obtain path for '" + aRelativePath
+                                       + "' for class " + aTestClass
+                                       + ", using relative path as is");
+                       return new File(aRelativePath);
+               }
+               URL location = source.getLocation();
+               String protocol = location.getProtocol();
+               if (!protocol.equals("file")) {
+                       LOG.warn("protocol is not 'file': " + location);
+                       return new File(aRelativePath);
+               }
+
+               String path = location.getPath();
+               try {
+                       path = URLDecoder.decode(location.getPath(), "UTF-8");
+               } catch (UnsupportedEncodingException e) {
+                       // ignore it.. just don't decode
+                       LOG.warn("Decoding path failed: '" + location.getPath() + "'", e);
+               }
+
+               return new File(new File(path).getParentFile(), aRelativePath);
+       }
+
+       /**
+        * Ensures that a directory hierarchy exists (recursively if needed). If it
+        * is not possible to create the directory, then the test case will fail.
+        * 
+        * @param aDir
+        *            Directory to create.
+        */
+       public static void createDir(File aDir) {
+               if (aDir.exists() && !aDir.isDirectory()) {
+                       TestCase.fail("'" + aDir
+                                       + "' already exists and is not a directory");
+               }
+               if (aDir.exists()) {
+                       return;
+               }
+               createDir(aDir.getParentFile());
+               TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir());
+       }
+
+       /**
+        * Creates a file in a directory.  
+        * @param aDir Directory path. Will be created if it does not exist. 
+        * @param aName Filename. 
+        * @param aContents Contents.
+        */
+       public static void createFile(File aDir, String aName, InputStream aContents) {
+               createDir(aDir);
+               try {
+                       OutputStream os = new FileOutputStream(new File(aDir, aName));
+                       copyStream(aContents, os);
+               } catch (IOException e) {
+                       e.printStackTrace();
+                       TestCase.fail(e.getMessage());
+               }
+       }
+
+       /**
+        * Gets the test output directory for a specific test class.
+        * 
+        * @param aTestClass
+        *            Test class.
+        * @return Test output directory.
+        */
+       public static File getTestOutputDir(Class aTestClass) {
+               File file = getPath(TEST_OUTPUT_DIR, aTestClass);
+               String className = aTestClass.getName();
+               String classRelPath = className.replaceAll("\\.", "/");
+               return new File(file, classRelPath);
+       }
+
+       /**
+        * Gets the test input directory for a specific test class.
+        * 
+        * @param aTestClass
+        *            Test class.
+        * @return Test input directory.
+        */
+       public static File getTestInputDir(Class aTestClass) {
+               File file = getPath(TEST_INPUT_DIR, aTestClass);
+               String packageName = aTestClass.getPackage().getName();
+               String packagePath = packageName.replaceAll("\\.", "/");
+               return new File(file, packagePath);
+       }
+
+       /**
+        * Creates a directory hierarchy for the output directory of a test class if
+        * needed.
+        * 
+        * @param aTestClass
+        *            Test class
+        * @return Test directory.
+        */
+       public static File createTestOutputDir(Class aTestClass) {
+               File file = getTestOutputDir(aTestClass);
+               createDir(file);
+               return file;
+       }
+
+       /**
+        * Gets a test output file name. This returns a File object representing the
+        * output file and ensures that the directory where the file will be created
+        * already exists.
+        * 
+        * @param aName
+        *            Name of the file.
+        * @param aTestClass
+        *            Test class.
+        * @return File.
+        */
+       public static File getTestOutputFile(String aName, Class aTestClass) {
+               File file = new File(getTestOutputDir(aTestClass), aName);
+               createDir(file.getParentFile());
+               return file;
+       }
+
+       public static String read(InputStream aIs) throws IOException {
+               try {
+                       StringBuffer buffer = new StringBuffer();
+                       int c;
+                       while ((c = aIs.read()) != -1) {
+                               buffer.append((char) c);
+                       }
+                       return buffer.toString();
+               } finally {
+                       aIs.close();
+               }
+       }
+
+       /**
+        * Copies an input stream to an output stream.
+        * 
+        * @param aIs
+        *            Input stream.
+        * @param aOs
+        *            Output stream.
+        */
+       public static void copyStream(InputStream aIs, OutputStream aOs) {
+               try {
+                       int c;
+                       while ((c = aIs.read()) != -1) {
+                               aOs.write(c);
+                       }
+                       aIs.close();
+                       aOs.close();
+               } catch (IOException e) {
+                       e.printStackTrace();
+                       Assert.fail(e.getMessage());
+               }
+       }
+
+       /**
+        * Recursively copy a directory.
+        * 
+        * @param aSrc
+        *            Source directory
+        * @param aTarget
+        *            Target directory.
+        */
+       public static void copyDir(File aSrc, File aTarget) {
+               Assert.assertTrue(aSrc.isDirectory());
+               Assert.assertTrue(!aTarget.exists());
+
+               aTarget.mkdirs();
+
+               File[] files = aSrc.listFiles();
+               for (int i = 0; i < files.length; i++) {
+                       File file = files[i];
+                       if (file.isDirectory()) {
+                               if (!file.getName().equals(".svn")) {
+                                       copyDir(new File(aSrc, file.getName()), new File(aTarget,
+                                                       file.getName()));
+                               }
+                       } else {
+                               copyFile(file, new File(aTarget, file.getName()));
+                       }
+               }
+       }
+
+       /**
+        * Copy a file. If copying fails then the testcase will fail.
+        * 
+        * @param aSrc
+        *            Source file.
+        * @param aTarget
+        *            Target file.
+        */
+       public static void copyFile(File aSrc, File aTarget) {
+
+               try {
+                       FileInputStream fis = new FileInputStream(aSrc);
+                       FileOutputStream fos = new FileOutputStream(aTarget);
+                       FileChannel fcin = fis.getChannel();
+                       FileChannel fcout = fos.getChannel();
+
+                       // map input file
+
+                       MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
+                                       fcin.size());
+
+                       // do the file copy
+                       fcout.write(mbb);
+
+                       // finish up
+
+                       fcin.close();
+                       fcout.close();
+                       fis.close();
+                       fos.close();
+               } catch (IOException e) {
+                       Assert.assertTrue("Copying file " + aSrc.getPath() + " to "
+                                       + aTarget.getPath() + " failed.", false);
+               }
+       }
+
+       /**
+        * Remove all files within a given directory including the directory itself.
+        * This only attempts to remove regular files and not directories within the
+        * directory. If the directory contains a nested directory, the deletion
+        * will fail. The test case will fail if this fails.
+        * 
+        * @param aDir
+        *            Directory to remove.
+        */
+       public static void deleteDir(File aDir) {
+               cleanDir(aDir);
+               delete(aDir);
+       }
+
+       /**
+        * Remove all regular files within a given directory.
+        * 
+        * @param outputDirName
+        */
+       public static void cleanDir(File aDir) {
+               if (!aDir.exists()) {
+                       return; // nothing to do.
+               }
+               File[] entries = aDir.listFiles();
+               for (int i = 0; i < entries.length; i++) {
+                       File file = entries[i];
+                       if (file.isFile()) {
+                               Assert.assertTrue("Could not delete " + entries[i].getPath(),
+                                               entries[i].delete());
+                       }
+               }
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java
new file mode 100644 (file)
index 0000000..1cf9478
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the stream resource. 
+ *
+ * @author Erik Brakkee
+ */
+public class StreamResourceTest extends TestCase {
+
+    /**
+     * Loads an existing resource. Verifies it is found.
+     * 
+     */
+    public void testResourceFound() throws IOException {
+        File file = new File(
+                FileSystemUtils.getTestInputDir(StreamResourceTest.class), 
+        "myresource.txt"); 
+        assertTrue(file.canRead()); 
+        InputStream fileIs = new FileInputStream(file);
+        InputResource resource = new StreamResource(fileIs);
+        InputStream is = resource.getInputStream();
+        String data = FileSystemUtils.read(is);
+        assertEquals("This is my resource", data);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/TestData.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/TestData.java
new file mode 100644 (file)
index 0000000..58bea68
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+
+import junit.framework.Assert;
+
+/**
+ * TestData provides a convenient interface for managing test output files.
+ * 
+ * @author Erik Brakkee
+ */
+public final class TestData {
+
+       private Object _testcase;
+       private File _root;
+
+       /**
+        * Test data to be constructed in the setUp of a test. {@link #clean()} must
+        * be called to make sure that this directory is empty before executing a
+        * test.
+        */
+       public TestData(Object aTestcase) {
+               _testcase = aTestcase;
+               _root = getTestRootDir(aTestcase);
+               FileSystemUtils.createDir(_root);
+       }
+
+       /**
+        * Obtain root directory of JUnit tests.
+        * 
+        * @return Directory name.
+        */
+       private static File getTestRootDir(Object aTestcase) {
+               return FileSystemUtils.getTestOutputDir(aTestcase.getClass());
+       }
+
+       public void createFile(String aRelative, String aFile, InputStream aContents) {
+               FileSystemUtils
+                               .createFile(new File(_root, aRelative), aFile, aContents);
+       }
+
+       public void createFile(String aFile, String aContents) {
+               createFile(".", aFile, aContents);
+       }
+
+       public void createFile(String aRelative, String aFile, String aContents) {
+               InputStream is = new ByteArrayInputStream(aContents.getBytes());
+               FileSystemUtils.createFile(new File(_root, aRelative), aFile, is);
+       }
+       
+       public void deleteFile(String aFile) {
+               deleteFile(".", aFile);
+       }
+
+       public void deleteFile(String aRelative, String aFile) {
+               FileSystemUtils.delete(new File(_root, aFile));
+       }
+
+       /**
+        * Returns a temporary directory.
+        * 
+        * @return Temporary directory.
+        */
+       public File getTmpDir() {
+               return new File(_root, "tmpdir");
+       }
+
+       /**
+        * Cleans up the test output directory.
+        */
+       public void clean() {
+               FileSystemUtils.deleteDirRecursively(_root);
+               FileSystemUtils.createDir(_root);
+       }
+
+       /**
+        * Recursively copy a directory contents to the test output directory.
+        * 
+        * @param sSrc
+        *            Source directory to copy.
+        */
+       public void copyDir(File aSrc) {
+               FileSystemUtils.copyDir(aSrc, _root);
+       }
+
+       /**
+        * Copies a classpath resource to a relative path in the test output
+        * directory.
+        * 
+        * @param aResource
+        *            Resource to copy.
+        * @param aRelativePath
+        *            Relative path.
+        */
+       public void copyResource(String aResource, String aRelativePath) {
+               try {
+                       InputStream is = new ClassPathResource(aResource).getInputStream();
+                       FileOutputStream fos = new FileOutputStream(new File(_root,
+                                       aRelativePath));
+                       FileSystemUtils.copyStream(is, fos);
+               } catch (IOException e) {
+                       e.printStackTrace();
+                       Assert.fail(e.getMessage());
+               }
+       }
+
+       /**
+        * Copies a resource to the root directory of the test output.
+        * 
+        * @param aResource
+        *            Resource.
+        */
+       public void copyResource(String aResource) {
+               String basename = new File(aResource).getName();
+               copyResource(aResource, basename);
+       }
+
+       public void createDir(String aRelative) {
+               FileSystemUtils.createDir(new File(_root, aRelative));
+       }
+
+       /**
+        * Deletes a file or directory relative to the test output root.
+        * 
+        * @param aRelative
+        *            Relative path. The testcase will fail if the file or directory
+        *            cannot be removed.
+        */
+       public void delete(String aRelative) {
+               FileSystemUtils.delete(new File(_root, aRelative));
+       }
+
+       /**
+        * Deletes a directory including its contents.
+        * 
+        * @param aRelative
+        *            Relative path.
+        */
+       public void deleteDir(String aRelative) {
+               FileSystemUtils.deleteDir(new File(_root, aRelative));
+       }
+
+       /**
+        * Deletes a directory recursively.
+        * 
+        * @param aRelative
+        *            Relative path.
+        */
+       public void deleteDirRecursively(String aRelative) {
+               FileSystemUtils.deleteDir(new File(_root, aRelative));
+       }
+
+       /**
+        * Gets the root of the test output directory.
+        * 
+        * @return Root of the test output.
+        */
+       public File getRoot() {
+               return _root;
+       }
+
+       /**
+        * Gets a file object for a relative path.
+        */
+       public File getFile(String aRelative) {
+               return new File(_root, aRelative);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/TestResource.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/io/TestResource.java
new file mode 100644 (file)
index 0000000..ec28290
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 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.wamblee.io;
+
+import java.io.File;
+
+
+/**
+ * Test resource for locating resources in the classpath.
+ */
+public class TestResource extends FileResource {
+   
+    /**
+     * Test class name. 
+     * @param aTestClass Test class. 
+     * @param aName Name of the file to look for. 
+     */
+    public TestResource(Class aTestClass, String aName) {
+        super(getFile(aTestClass, aName)); 
+    }
+    
+    /**
+     * Computes the file path of the file to look for. 
+     * @param aClass Test class name. 
+     * @param aName Name of the file. 
+     * @return File. 
+     */
+    private static File getFile(Class aClass, String aName) { 
+        File dir = FileSystemUtils.getTestInputDir(aClass);
+        return new File(dir, aName);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/observer/ObservableTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/observer/ObservableTest.java
new file mode 100644 (file)
index 0000000..8a060e8
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright 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.wamblee.observer;
+
+import static org.mockito.Mockito.*; 
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mockito.InOrder;
+
+import junit.framework.TestCase;
+
+/**
+ * Test of the observer pattern implementation.
+ * 
+ * @author Erik Brakkee
+ */
+public class ObservableTest extends TestCase {
+
+       private static final int SUBSCRIBER_COUNT = 100;
+
+       private static final String UPDATE = "send";
+
+       private Integer _observed;
+       private Observable<Integer, String> _observable;
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see junit.framework.TestCase#setUp()
+        */
+       @Override
+       protected void setUp() throws Exception {
+               super.setUp();
+               _observed = new Integer(1);
+               _observable = new Observable<Integer, String>(_observed,
+                               new DefaultObserverNotifier());
+       }
+
+       /**
+        * Tests subscription and notification of one subscriber.
+        */
+       public void testOneObserver() {
+               final Observer mockObserver = mock(Observer.class);
+               InOrder order = inOrder(mockObserver);
+               
+               long subscription = _observable.subscribe(mockObserver);
+
+               assertEquals(1, _observable.getObserverCount());
+
+               final String message = "hallo";
+               _observable.send(message);
+               
+               order.verify(mockObserver).send(_observed, message);
+               verifyNoMoreInteractions(mockObserver);
+               
+               _observable.unsubscribe(subscription);
+               assertEquals(0, _observable.getObserverCount());
+
+               _observable.send(message);
+               verifyNoMoreInteractions(mockObserver);
+       }
+
+       /**
+        * Subscribes many susbcribers and sends notifications to subscribers.
+        * Verifies that unique subscription number are returned. Also verifies that
+        * the correct subscribers are notfied.
+        */
+       public void testManySubscribers() {
+               final int nsubscribers = SUBSCRIBER_COUNT;
+               final Observer[] mocks = new Observer[nsubscribers];
+               final InOrder[] order = new InOrder[nsubscribers];
+
+               List<Long> subscriptions = new ArrayList<Long>();
+               for (int i = 0; i < nsubscribers; i++) {
+                       mocks[i] = mock(Observer.class);
+                       order[i] = inOrder(mocks[i]);
+                       long subscription = _observable.subscribe(mocks[i]);
+                       assertTrue(subscriptions.add(subscription));
+               }
+
+               assertEquals(nsubscribers, _observable.getObserverCount());
+
+               final String message = "hallo";
+
+               _observable.send(message);
+               for (int i = 0; i < nsubscribers; i++) {
+                       order[i].verify(mocks[i]).send(_observed, message);
+               }
+
+               for (int i = nsubscribers / 2; i < nsubscribers; i++) {
+                       _observable.unsubscribe(subscriptions.get(i));
+               }
+               assertEquals(nsubscribers - (nsubscribers - nsubscribers / 2),
+                               _observable.getObserverCount());
+
+               final String message2 = "blabla";
+
+               _observable.send(message2);
+               for (int i = 0; i < nsubscribers / 2; i++) {
+                       order[i].verify(mocks[i]).send(_observed, message2);
+               }               
+               for (int i = nsubscribers/2; i < nsubscribers; i++) {
+                       verifyNoMoreInteractions(mocks[i]);
+               }               
+               
+       }
+
+       /**
+        * Subscribes and then unsubscribes with a wrong id. Verifies that
+        * IllegalArgumentException is thrown.
+        * 
+        */
+       public void testUnsubscribeWithWrongSubscription() {
+               Observer<Integer, String> observer = mock(Observer.class);
+       
+               long subscription = _observable.subscribe(observer);
+
+               assertEquals(1, _observable.getObserverCount());
+
+               try {
+                       _observable.unsubscribe(subscription + 1);
+               } catch (IllegalArgumentException e) {
+                       return; // ok
+               }
+               fail();
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/AssertionUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/AssertionUtils.java
new file mode 100644 (file)
index 0000000..a0216a8
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ * Copyright 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.wamblee.test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Useful assertions for use in test cases.
+ *
+ * @author Erik Brakkee
+ */
+public final class AssertionUtils {
+       
+       private static final Log LOG = LogFactory.getLog(AssertionUtils.class);
+
+    /**
+     * Disabled constructor.
+     * 
+     */
+    private AssertionUtils() {
+        // Empty
+    }
+    
+    /**
+     * Asserts that two object arrays are equal.
+     * 
+     * @param aExpected
+     *            Expected object array.
+     * @param aActual
+     *            Actual object array.
+     */
+    public static <T> void assertEquals(T[] aExpected, T[] aActual) {
+        assertEquals("", aExpected, aActual);
+    }
+    
+
+    /**
+     * Asserts that two object arrays are equal.
+     * 
+     * @param aMsg
+     *            Message.
+     * @param aExpected
+     *            Expected array.
+     * @param aActual
+     *            Actual array.
+     */
+    public static <T> void assertEquals(String aMsg, T[] aExpected,
+            T[] aActual) {
+        TestCase.assertEquals(aMsg + " expected " + 
+                Arrays.asList(aExpected) + ", actual " + 
+                Arrays.asList(aActual) + ": Array lengths ", aExpected.length,
+                aActual.length);
+
+        for (int i = 0; i < aExpected.length; i++) {
+            TestCase.assertEquals(aMsg + ": Element " + i, aExpected[i],
+                    aActual[i]);
+        }
+    }
+    
+
+    /**
+     * Asserts that two objects are equal, and in case the object is an Object[]
+     * delegates to {@link #assertEquals(String, Object[], Object[]).
+     * 
+     * @param aMsg
+     *            Message.
+     * @param aExpected
+     *            Expected result.
+     * @param aActual
+     *            Actual result.
+     */
+    public static <T> void assertEquals(String aMsg, T aExpected,
+            T aActual) {
+        if (aExpected instanceof Object[]) {
+            AssertionUtils.assertEquals(aMsg, (Object[]) aExpected,
+                    (Object[]) aActual);
+
+            return;
+        }
+
+        TestCase.assertEquals(aMsg, aExpected, aActual);
+    }
+
+    /**
+     * Asserts that two maps are equal by comparing all keys and by checking
+     * that the values for the same keys are the same.
+     * 
+     * @param aMsg
+     *            Message.
+     * @param aExpectedMap
+     *            Expected result.
+     * @param aActual
+     *            Actual result.
+     */
+    public static <Key,Value> void assertEquals(String aMsg, 
+            Map<Key,Value> aExpectedMap, Map<Key,Value> aActual) {
+        TestCase.assertEquals("Map sizes differ", aExpectedMap.size(), aActual
+                .size());
+
+        Set keys = aExpectedMap.keySet();
+
+        for (Iterator i = keys.iterator(); i.hasNext();) {
+            String key = (String) i.next();
+            TestCase.assertTrue("Map does not containg entry for key:" + key,
+                    aActual.containsKey(key));
+            AssertionUtils.assertEquals("Value of key " + key + " of map",
+                    aExpectedMap.get(key), aActual.get(key));
+        }
+    }
+   
+    public static interface ErroneousCode { 
+       void run() throws Exception; 
+    }
+    
+    /** 
+     * Asserts that an exception occurs.
+     * @param aRunnable Test cases should create a subclass of this which contains the 
+     * code that should throw an exception.   
+     * @param aType Type of exception that is expected.   
+     */
+    public static void assertException(ErroneousCode aObject, Class aType) { 
+       try { 
+               aObject.run();
+               throw new RuntimeException("No exception occurred");
+       } catch (Throwable t) { 
+               if ( aType.isInstance(t)) { 
+                       LOG.info("Expected exception occured " + t.getMessage());
+                       return; // ok 
+               }
+               else { 
+                       throw new RuntimeException(t);
+               }
+       }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/EventTracker.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/EventTracker.java
new file mode 100644 (file)
index 0000000..333da1e
--- /dev/null
@@ -0,0 +1,146 @@
+/*
+ * Copyright 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.wamblee.test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Tracks the occurence of certain events in a test environment. Threads in a
+ * test environment tell the event tracker of the occurrence of certain events
+ * using {@link #eventOccurred(Event)}. Test code inspects the events sent by a
+ * thread using {@link #isEventSent(Thread, Event)}.
+ * 
+ * A record is kept of every event which is sent. Therefore, the occurrence of a
+ * new event does not erase a previously sent event.
+ * 
+ * @param <Event>
+ *            Type of event sent from test code. Usually String will be
+ *            sufficient. The event type must provide a sensible implementation
+ *            of {@link java.lang.Object#equals(java.lang.Object)}.
+ *
+ * @author Erik Brakkee
+ */
+public class EventTracker<Event> {
+
+    private static final Log LOG = LogFactory.getLog(EventTracker.class);
+
+    /**
+     * Map of Thread object to a list of events.
+     */
+    private Map<Thread, List<Event>> _events;
+
+    /**
+     * Constructs the event tracker.
+     * 
+     */
+    public EventTracker() {
+        clear();
+    }
+
+       public void clear() {
+               _events = new HashMap<Thread, List<Event>>();
+       }
+
+    /**
+     * Called by a thread to inform that an event has occurred.
+     * 
+     * @param aEvent
+     *            Event that was sent.
+     */
+    public synchronized void eventOccurred(Event aEvent) {
+        LOG.info("Event '" + aEvent + "' sent.");
+        Thread current = Thread.currentThread();
+        List<Event> events = _events.get(current);
+        if (events == null) {
+            events = new ArrayList<Event>();
+            _events.put(current, events);
+        }
+        events.add(aEvent);
+    }
+
+    /**
+     * Checks if a specific event has happened in a specific thread.
+     * 
+     * @param aThread
+     *            Thread to check.
+     * @param aEvent
+     *            Event to check for.
+     * @return Whether or not the event was sent.
+     */
+    public synchronized boolean isEventSent(Thread aThread, Event aEvent) {
+        List<Event> events = _events.get(aThread);
+        if (events == null) {
+            return false;
+        }
+        return events.contains(aEvent);
+    }
+
+    /**
+     * Gets the events for a thread in the order they were sent
+     * 
+     * @param aThread
+     *            Thread to get events for.
+     * @return Events that were sent. A zero-sized array is returned if no
+     *         events were sent.
+     */
+    public synchronized List<Event> getEvents(Thread aThread) {
+        List<Event> events = _events.get(aThread);
+        if (events == null) {
+            events = Collections.emptyList();
+        }
+        return Collections.unmodifiableList(events);
+    }
+
+    /**
+     * Gets the number of times an event was sent summed up
+     * over all threads. 
+     * 
+     * @param aEvent
+     *            Event to check.
+     * @return Number of times it was reached.
+     */
+    public synchronized int getEventCount(Event aEvent) {
+        int count = 0;
+        for (Thread thread : _events.keySet()) {
+            List<Event> events = _events.get(thread);
+            for (Event event : events) {
+                if (event.equals(aEvent)) {
+                    count++;
+                }
+            }
+        }
+        return count;
+    }
+    
+    /**
+     * Gets the total event count over all threads. 
+     * @return
+     */
+    public synchronized int getEventCount() { 
+       int count = 0; 
+       for (Thread thread: _events.keySet()) { 
+               count += _events.get(thread).size();
+       }
+       return count; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/TimingUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/test/TimingUtils.java
new file mode 100644 (file)
index 0000000..82d3c0e
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright 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.wamblee.test;
+
+import junit.framework.TestCase;
+
+/**
+ * Timing utilities.
+ *
+ * @author Erik Brakkee
+ */
+public final class TimingUtils {
+
+    /**
+     * Disabled constructor.
+     *
+     */
+    private TimingUtils() {
+        // Empty
+    }
+    
+    /**
+     * Sleeps for a time. 
+     * @param aMillis Number of milliseconds to sleep. 
+     */
+    public static void sleep(int aMillis) { 
+        try { 
+            Thread.sleep(aMillis);
+        } catch (InterruptedException e) { 
+            TestCase.fail("Who interrupted my sleep?");
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java
new file mode 100644 (file)
index 0000000..39280c6
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+import java.io.IOException;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.stream.StreamSource;
+
+import junit.framework.TestCase;
+
+
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.FileSystemUtils;
+
+/**
+ * Tests for {@link org.wamblee.xml.ClasspathUriResolver}.
+ *
+ * @author Erik Brakkee
+ */
+public class ClasspathUriResolverTest extends TestCase {
+    
+    private URIResolver _resolver; 
+    
+    /* (non-Javadoc)
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        _resolver = new ClasspathUriResolver();        
+    }
+
+    /**
+     * Resolves an existing file. Verifies the file is resolved correctly. 
+     * @throws TransformerException 
+     * @throws IOException
+     */
+    public void testResolveExistingFile() throws TransformerException, IOException { 
+        Source source = _resolver.resolve("org/wamblee/xml/reportToHtml.xsl", "");
+        assertTrue(source instanceof StreamSource);
+        String resolved = FileSystemUtils.read(((StreamSource)source).getInputStream());
+        
+        ClassPathResource resource = new ClassPathResource("org/wamblee/xml/reportToHtml.xsl");
+        String expected = FileSystemUtils.read(resource.getInputStream());
+        assertEquals(expected, resolved);
+    }
+    
+    /**
+     * Resolves a non-existing file. Verifies that a TransformerException is thrown. 
+     *
+     */
+    public void testResolveNonExistingFile() {
+        try { 
+            Source source = _resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl", "");
+        } catch (TransformerException e) { 
+            return; // ok
+        }
+        fail();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/XmlUtils.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/XmlUtils.java
new file mode 100644 (file)
index 0000000..fc89425
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import junit.framework.TestCase;
+
+import org.dom4j.Attribute;
+import org.dom4j.Document;
+import org.dom4j.Element;
+
+/**
+ * XML test support utilities.
+ *
+ * @author Erik Brakkee
+ */
+public final class XmlUtils {
+
+    /**
+     * Disabled constructor.
+     * 
+     */
+    private XmlUtils() {
+        // Empty
+    }
+
+    /**
+     * Checks equality of two XML documents excluding comment and processing
+     * nodes and trimming the text of the elements. In case of problems, it
+     * provides an xpath-like expression describing where the problem is.  
+     * 
+     * @param aMsg
+     * @param aExpected
+     * @param aActual
+     */
+    public static void assertEquals(String aMsg,
+            org.w3c.dom.Document aExpected, org.w3c.dom.Document aActual) {
+        assertEquals(aMsg, DomUtils.convert(aExpected), DomUtils
+                .convert(aActual));
+    }
+
+    /**
+     * Checks equality of two XML documents excluding comment and processing
+     * nodes and trimming the text of the elements.  In case of problems, it
+     * provides an xpath-like expression describing where the problem is.  
+     * 
+     * @param aMsg
+     * @param aExpected
+     * @param aActual
+     */
+    public static void assertEquals(String aMsg, Document aExpected,
+            Document aActual) {
+        assertEquals(aMsg + "/" + aExpected.getRootElement().getName(), aExpected.getRootElement(), aActual.getRootElement());
+    }
+
+    /**
+     * Checks equality of two XML elements excluding comment and processing
+     * nodes and trimming the text of the elements. In case of problems, it
+     * provides an xpath-like expression describing where the problem is.  
+     * 
+     * @param aMsg
+     * @param aExpected
+     * @param aActual
+     */
+    public static void assertEquals(String aMsg, Element aExpected,
+            Element aActual) {
+
+        // Name.
+        TestCase.assertEquals(aMsg + "/name()", aExpected.getName(), aActual
+                .getName());
+
+        // Text
+        TestCase.assertEquals(aMsg + "/text()", aExpected.getTextTrim(),
+                aActual.getTextTrim());
+
+        // Attributes
+        List<Attribute> expectedAttrs = aExpected.attributes();
+        Collections.sort(expectedAttrs, new AttributeComparator());
+        List<Attribute> actualAttrs = aActual.attributes();
+        Collections.sort(actualAttrs, new AttributeComparator());
+
+        TestCase.assertEquals("count(" + aMsg + "/@*)", expectedAttrs.size(),
+                actualAttrs.size());
+        for (int i = 0; i < expectedAttrs.size(); i++) {
+            String msg = aMsg + "/@" + expectedAttrs.get(i).getName();
+            assertEquals(msg, expectedAttrs.get(i), actualAttrs.get(i));
+        }
+
+        // Nested elements.
+        List<Element> expectedElems = aExpected.elements();
+        List<Element> actualElems = aActual.elements();
+        TestCase.assertEquals("count(" + aMsg + "/*)", expectedElems.size(),
+                actualElems.size());
+        // determine the how-manyth element of the given name we are at.
+        // Maps element name to the last used index (or null if not yet used)
+        Map<String, Integer> elementIndex = new TreeMap<String, Integer>();
+        for (int i = 0; i < expectedElems.size(); i++) {
+            String elemName = expectedElems.get(i).getName();
+            Integer index = elementIndex.get(elemName);
+            if (index == null) {
+                index = 1;
+            } else {
+                index++;
+            }
+            elementIndex.put(elemName, index);
+            String msg = aMsg + "/" + expectedElems.get(i).getName() + "["
+                    + index + "]";
+
+            assertEquals(msg, expectedElems.get(i), actualElems.get(i));
+        }
+    }
+
+    /**
+     * Checks equality of two attributes. In case of problems, it
+     * provides an xpath-like expression describing where the problem is.  
+     * 
+     * @param aMsg
+     * @param aExpected
+     * @param aActual
+     */
+    public static void assertEquals(String aMsg, Attribute aExpected,
+            Attribute aActual) {
+        TestCase.assertEquals(aMsg + ":name", aExpected.getName(), aActual
+                .getName());
+        TestCase.assertEquals(aMsg + ":value", aExpected.getValue(), aActual
+                .getValue());
+    }
+
+    /**
+     * Comparator which compares attributes by name.
+     */
+    private static final class AttributeComparator implements
+            Comparator<Attribute> {
+        /*
+         * (non-Javadoc)
+         * 
+         * @see java.util.Comparator#compare(T, T)
+         */
+        public int compare(Attribute aAttribute1, Attribute aAttribute2) {
+            return aAttribute1.getName().compareTo(aAttribute2.getName());
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java b/tags/wamblee-utils-0.2.1/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java
new file mode 100644 (file)
index 0000000..d30e60a
--- /dev/null
@@ -0,0 +1,257 @@
+/*
+ * Copyright 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.wamblee.xml;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import junit.framework.TestCase;
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.FileSystemUtils;
+import org.wamblee.io.InputResource;
+
+import org.w3c.dom.Document;
+
+/**
+ * Tests the XSL transformer.
+ *
+ * @author Erik Brakkee
+ */
+public class XslTransformerTest extends TestCase {
+
+    private static final String INCLUDED_XSL_FILE = "utilities.xsl";
+
+       private static final String REPORT_XML = "report.xml";
+
+    private static final String REPORT_TO_HTML_XSLT = "reportToHtml.xsl";
+
+    private static final String REPORT_TO_HTML2_XSLT = "reportToHtml2.xsl";
+    
+    private static final String REPORT_TO_HTML_INVALID_XSLT = "reportToHtml-invalid.xsl";
+    
+    private static final String REPORT_TO_HTML_NONWELLFORMED_XSLT = "reportToHtml-nonwellformed.xsl";
+    
+    private static final String REPORT_TO_TEXT_XSLT = "reportToText.xsl";
+
+    private String getResourcePath(String aResource) { 
+       return getClass().getPackage().getName().replaceAll("\\.", "/") + "/" + aResource;
+    }
+
+    /**
+     * Transforms a file while using the default resolver, where the included
+     * file can be found. Verifies the transformation is done correctly.
+     * 
+     */
+    public void testTransformUsingDefaultResolver() throws Exception {
+        XslTransformer transformer = new XslTransformer();
+
+        InputResource xmlResource = new ClassPathResource(getResourcePath(REPORT_XML));
+        
+        Source xslt = new StreamSource(new ClassPathResource(getResourcePath(
+                       REPORT_TO_HTML_XSLT)).getInputStream());
+
+        byte[] documentData = FileSystemUtils
+                .read(xmlResource.getInputStream()).getBytes();
+        DocumentBuilder builder = DocumentBuilderFactory.newInstance()
+                .newDocumentBuilder();
+        Document document = builder.parse(xmlResource.getInputStream());
+        Source documentSource = new StreamSource(xmlResource.getInputStream());
+
+        Document expected = DomUtils.read(new ClassPathResource(getResourcePath(
+                       "output-reportToHtml-report.xml")).getInputStream());
+
+        Document output1 = transformer.transform(documentData, xslt);
+        XmlUtils.assertEquals("byte[] transform", expected, output1);
+
+        xslt = new StreamSource(new ClassPathResource(getResourcePath(
+                       REPORT_TO_HTML_XSLT)).getInputStream());
+        Document output2 = transformer.transform(document, xslt);
+        XmlUtils.assertEquals("document transform", expected, output2);
+
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        Result output = new StreamResult(os);
+        
+        xslt = new StreamSource(new ClassPathResource(getResourcePath(
+                       REPORT_TO_HTML_XSLT)).getInputStream());
+        transformer.transform(documentSource, output, xslt);
+        XmlUtils.assertEquals("document source transform", expected, DomUtils
+                .read(os.toString()));
+
+        xslt = new StreamSource(new ClassPathResource(getResourcePath(
+                       REPORT_TO_HTML_XSLT)).getInputStream());
+        String result = transformer.textTransform(documentData, xslt);
+        XmlUtils
+                .assertEquals("text transform", expected, DomUtils.read(result));
+    }
+
+    /**
+     * Transforms a file using the default resolver where the included file
+     * cannot be found. Verifies that a TransformerException is thrown.
+     * 
+     */
+    public void testTransformUsingDefaultResolverFails() throws IOException {
+        XslTransformer transformer = new XslTransformer();
+
+        InputResource xmlResource = 
+                       new ClassPathResource(getResourcePath(REPORT_XML));
+        Source xslt = new StreamSource(
+                       new ClassPathResource(getResourcePath(
+                                       REPORT_TO_HTML2_XSLT)).getInputStream());
+
+        byte[] documentData = FileSystemUtils
+                .read(xmlResource.getInputStream()).getBytes();
+        try {
+            Document output1 = transformer.transform(documentData, xslt);
+        } catch (TransformerException e) {
+            return; // ok
+        }
+        fail();
+    }
+
+    /**
+     * Transforms a file using an invalid Xslt. Verifies that a
+     * TransformerException is thrown.
+     * 
+     */
+    public void testTransformInvalidXslt() throws IOException {
+        XslTransformer transformer = new XslTransformer();
+
+        InputResource xmlResource = new ClassPathResource(
+                       getResourcePath(REPORT_XML));
+        Source xslt = new StreamSource(
+                       new ClassPathResource(getResourcePath(REPORT_TO_HTML_INVALID_XSLT)).getInputStream());
+
+        byte[] documentData = FileSystemUtils
+                .read(xmlResource.getInputStream()).getBytes();
+        try {
+            Document output1 = transformer.transform(documentData, xslt);
+        } catch (TransformerException e) {
+            return; // ok
+        }
+        fail();
+    }
+
+    /**
+     * Transforms a file using a non-well formed xslt. Verifies that a
+     * TransformerException is thrown.
+     * 
+     */
+    public void testTransformNonWellformedXslt() throws IOException {
+        XslTransformer transformer = new XslTransformer();
+
+        InputResource xmlResource = new ClassPathResource(
+                       getResourcePath(REPORT_XML));
+        Source xslt = new StreamSource(
+                       new ClassPathResource(getResourcePath(
+                                       REPORT_TO_HTML_NONWELLFORMED_XSLT)).getInputStream());
+
+        byte[] documentData = FileSystemUtils
+                .read(xmlResource.getInputStream()).getBytes();
+        try {
+            Document output1 = transformer.transform(documentData, xslt);
+        } catch (TransformerException e) {
+            return; // ok
+        }
+        fail();
+    }
+
+    /**
+     * Transforms a file using a class path resolver.
+     * 
+     */
+    public void testTransformUsingClassPathResolver() throws Exception {
+        XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
+
+        InputResource xmlResource = new ClassPathResource(getResourcePath(
+                       REPORT_XML));
+        Source xslt = new StreamSource(new ClassPathResource(
+                       getResourcePath(REPORT_TO_HTML2_XSLT)).getInputStream());
+
+        byte[] documentData = FileSystemUtils
+                .read(xmlResource.getInputStream()).getBytes();
+        
+        Document output1 = transformer.transform(documentData, xslt);
+        Document expected = DomUtils.read(new ClassPathResource(
+                       getResourcePath("output-reportToHtml-report.xml"))
+                .getInputStream());
+        XmlUtils.assertEquals("doc", expected, output1);
+    }
+
+    /**
+     * Transforms a file to text output. Verifies the file is transformed
+     * correctly.
+     * 
+     */
+    public void testTransformToTextOutput() throws Exception {
+        XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
+
+        InputResource xmlResource = new ClassPathResource(
+                       getResourcePath(REPORT_XML));
+        Source xslt = new StreamSource(
+                       new ClassPathResource(getResourcePath(REPORT_TO_TEXT_XSLT)).getInputStream());
+
+        byte[] documentData = FileSystemUtils
+                .read(xmlResource.getInputStream()).getBytes();
+   
+        String result = transformer.textTransform(documentData, xslt);
+        String expected = "Hello world!";
+        assertEquals("text transform", expected, result);
+    }
+    /**
+     * Tests resolving a file using {@link XslTransformer#resolve(String)} with the 
+     * default resolver where the file does not exist. 
+     *
+     */
+    public void testResolveWithDefaultResolverFileNotFound() { 
+        XslTransformer transformer = new XslTransformer();
+        try { 
+            Source source = transformer.resolve("org/wamblee/xml/utilities-nonexistent.xsl");
+        } catch (TransformerException e) { 
+            return; // ok
+        }
+        fail();
+    }
+    
+    
+    /**
+     * Tests resolving a file using {@link XslTransformer#resolve(String)} with the 
+     * default resolver. 
+     *
+     */
+    public void testResolveWithClasspathResolver() throws Exception { 
+        XslTransformer transformer = new XslTransformer(new ClasspathUriResolver());
+        Source source = transformer.resolve(getResourcePath(INCLUDED_XSL_FILE));
+        assert(source instanceof StreamSource);
+        StreamSource ssource = (StreamSource)source;
+        String data = FileSystemUtils.read(ssource.getInputStream());
+        String expected = FileSystemUtils.read(new ClassPathResource(getResourcePath(INCLUDED_XSL_FILE)).getInputStream());
+        assertEquals(expected, data);
+    }
+    
+}
+
+    
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/cache/ehcache.xml b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/cache/ehcache.xml
new file mode 100644 (file)
index 0000000..694184e
--- /dev/null
@@ -0,0 +1,64 @@
+<ehcache>
+
+    <!-- Sets the path to the directory where cache .data files are created.
+
+         If the path is a Java System Property it is replaced by
+         its value in the running VM.
+
+         The following properties are translated:
+         user.home - User's home directory
+         user.dir - User's current working directory
+         java.io.tmpdir - Default temp file path -->
+    <diskStore path="java.io.tmpdir"/>
+
+
+    <!--Default Cache configuration. These will applied to caches programmatically created through
+        the CacheManager.
+
+        The following attributes are required:
+
+        maxElementsInMemory            - Sets the maximum number of objects that will be created in memory
+        eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
+                                         element is never expired.
+        overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
+                                         has reached the maxInMemory limit.
+
+        The following attributes are optional:
+        timeToIdleSeconds              - Sets the time to idle for an element before it expires.
+                                         i.e. The maximum amount of time between accesses before an element expires
+                                         Is only used if the element is not eternal.
+                                         Optional attribute. A value of 0 means that an Element can idle for infinity.
+                                         The default value is 0.
+        timeToLiveSeconds              - Sets the time to live for an element before it expires.
+                                         i.e. The maximum time between creation time and when an element expires.
+                                         Is only used if the element is not eternal.
+                                         Optional attribute. A value of 0 means that and Element can live for infinity.
+                                         The default value is 0.
+        diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
+                                         The default value is false.
+        diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
+                                         is 120 seconds.
+        -->
+
+    <defaultCache
+        maxElementsInMemory="10000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="5"
+        timeToLiveSeconds="5"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+        />
+        
+    <cache
+        name="test"
+        maxElementsInMemory="10000"
+        eternal="false"
+        overflowToDisk="false"
+        timeToIdleSeconds="5"
+        timeToLiveSeconds="5"
+        diskPersistent="false"
+        diskExpiryThreadIntervalSeconds="120"
+    />
+    
+</ehcache>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beanRefContext.xml b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beanRefContext.xml
new file mode 100644 (file)
index 0000000..a453f3d
--- /dev/null
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+ <beans> 
+     
+     <bean id="test"
+         class="org.springframework.context.support.ClassPathXmlApplicationContext">
+         <constructor-arg>
+             <list>
+               <value>org/wamblee/general/spring1.xml</value>
+             </list>
+         </constructor-arg>
+     </bean>
+     
+ </beans>
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beankernel-wrong.properties b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beankernel-wrong.properties
new file mode 100644 (file)
index 0000000..e54de19
--- /dev/null
@@ -0,0 +1,2 @@
+
+org.wamblee.beanfactory.class=org.wamblee.general.TestBeanFactoryBla
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beankernel.properties b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/beankernel.properties
new file mode 100644 (file)
index 0000000..e08cf39
--- /dev/null
@@ -0,0 +1,2 @@
+
+org.wamblee.beanfactory.class=org.wamblee.general.TestBeanFactory
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/spring1.xml b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/general/spring1.xml
new file mode 100644 (file)
index 0000000..52ec0be
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+
+<beans>
+  
+    <bean id="java.lang.String"
+          class="java.lang.String">
+        <constructor-arg><value>hello</value></constructor-arg>
+    </bean>  
+  
+</beans> 
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/io/myresource.txt b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/io/myresource.txt
new file mode 100644 (file)
index 0000000..c72f110
--- /dev/null
@@ -0,0 +1 @@
+This is my resource
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/output-reportToHtml-report.xml b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/output-reportToHtml-report.xml
new file mode 100644 (file)
index 0000000..40f29fd
--- /dev/null
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="utf-8"?>
+<html>
+    <head>
+        <title>KiSS crawler report</title>
+    </head>
+    <body>
+        <h1>KiSS crawler report</h1>
+        <h2>Successfully recorded programs <p>
+                <table align="left" cellpadding="5">
+                    <tr align="left">
+                        <td>23:25 - 00:10: <strong>Wintertijd</strong> (Nederland
+                        1/Documentaire)</td>
+                    </tr>
+                    <tr>
+                        <td>
+                            <blockquote>
+                                <font size="-1">Some description MINSK - De presidentsverkiezingen
+                                    in Wit-Rusland zijn zondag met ruime cijfers gewonnen door
+                                    zittend president Aleksandr Loekasjenko. Dat bleek zondag uit
+                                    exitpolls uitgevoerd in opdracht van het totalitaire regime. Het
+                                    staatshoofd zou kunnen rekenen op ruim 82 procent van de
+                                    stemmen. Volgens de eerste gedeeltelijke uitslagen zou
+                                    Loekasjenko zelfs kunnen rekenen op bijna 89 procent. </font>
+                            </blockquote>
+                        </td>
+                    </tr>
+                </table>
+                <br clear="left"/>
+            </p></h2>
+        <h2>Possibly interesting programs</h2>
+        <p>
+            <table align="left" cellpadding="5">
+                <tr align="left">
+                    <td>23:30 - 00:15: <strong>Brainiac</strong> (Discovery Channel/science)</td>
+                </tr>
+                <tr>
+                    <td>
+                        <blockquote>
+                            <font size="-1">Humor</font>
+                        </blockquote>
+                    </td>
+                </tr>
+            </table>
+            <br clear="left"/>
+        </p>
+        <h3>Category: horror</h3>
+        <p>
+            <table align="left" cellpadding="5">
+                <tr align="left">
+                    <td>23:30 - 00:15: <strong>Andere tijden</strong> (Nederland 1/docu)</td>
+                </tr>
+                <tr>
+                    <td>
+                        <blockquote>
+                            <font size="-1">Documentaire</font>
+                        </blockquote>
+                    </td>
+                </tr>
+            </table>
+            <br clear="left"/>
+        </p>
+    </body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/report.xml b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/report.xml
new file mode 100644 (file)
index 0000000..391aea9
--- /dev/null
@@ -0,0 +1,41 @@
+<report>
+    <recorded result="OK">
+        <program>
+            <name>Wintertijd</name>
+            <description>Some description MINSK - De presidentsverkiezingen in Wit-Rusland zijn zondag met ruime cijfers gewonnen door zittend president Aleksandr Loekasjenko. Dat bleek zondag uit exitpolls uitgevoerd in opdracht van het totalitaire regime. Het staatshoofd zou kunnen rekenen op ruim 82 procent van de stemmen. Volgens de eerste gedeeltelijke uitslagen zou Loekasjenko zelfs kunnen rekenen op bijna 89 procent. </description>
+            <keywords>Documentaire</keywords>
+            <channel>Nederland 1</channel>
+            <interval>
+                <begin>23:25</begin>
+                <end>00:10</end>
+            </interval>
+        </program>    
+    </recorded>
+    
+    <interesting>
+        <program>
+            <name>Brainiac</name>
+            <description>Humor</description>
+            <keywords>science</keywords>
+            <channel>Discovery Channel</channel>
+            <interval>
+                <begin>23:30</begin>
+                <end>00:15</end>
+            </interval>
+        </program>
+        <category name="horror">
+            <program>
+                <name>Andere tijden</name>
+                <description>Documentaire</description>
+                <keywords>docu</keywords>
+                <channel>Nederland 1</channel>
+                <interval>
+                    <begin>23:30</begin>
+                    <end>00:15</end>
+                </interval>
+            </program>
+        </category>
+        
+    </interesting>
+  
+</report>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml-invalid.xsl b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml-invalid.xsl
new file mode 100644 (file)
index 0000000..104234e
--- /dev/null
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+<xsl:output method="xml"/>
+    <xsl:template match="report">
+        <html>
+            <head>
+                <title>KiSS crawler report</title>
+            </head>
+            <body>
+                <h1>KiSS crawler report</h1>
+                <xsl:apply-templates select="recorded"/>
+                <xsl:ifdd test="count(interesting) > 0">
+                    <h2>Possibly interesting programs</h2>
+                    <xsl:apply-templates select="interesting"/>
+                </xsl:ifdd>
+                <xsl:if test="count(//program) = 0">
+                    <xsl:text>No suitable programs found </xsl:text>
+                </xsl:if>
+            </body>
+        </html>
+
+    </xsl:template>
+
+    <xsl:template name="programTable">
+        <p>
+        <table align="left" cellpadding="5">
+            <!-- 
+            <tr align="left">
+                <th align="left">Time</th>
+                <th align="left">Channel</th>
+                <th align="left">Program</th>
+            </tr>
+            -->
+            <xsl:apply-templates select="program"/>
+        </table>
+        <br clear="left"/>
+        </p>
+    </xsl:template>
+
+    <xsl:template match="recorded">
+        <h2>
+            <xsl:choose>
+                <xsl:when test="@result = 'OK'">
+                    <xsl:text>Successfully recorded programs </xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'DUPLICATE'">
+                    <xsl:text>Already recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'CONFLICT'">
+                    <xsl:text>Conflicts with other recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result='ERROR'">
+                    <xsl:text>Programs that could not be recorded for
+                    technical reasons.</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+            </xsl:choose>
+        </h2>
+    </xsl:template>
+
+    <xsl:template name="addProgramInfo">
+        <tr align="left">
+            <td><xsl:value-of select="interval/begin"/> - <xsl:value-of select="interval/end"/>: <strong>
+                    <xsl:value-of select="name"/>
+                </strong> (<xsl:value-of select="channel"/>/<xsl:value-of select="keywords"/>)</td>
+
+        </tr>
+        <tr>
+            <td>
+                <blockquote>
+                        <font size="-1">
+                            <xsl:value-of select="description"/>
+                        </font>
+                </blockquote>
+            </td>
+
+
+        </tr>
+    </xsl:template>
+
+    <xsl:template match="program">
+        <xsl:call-template name="addProgramInfo"/>
+    </xsl:template>
+
+    <xsl:template match="interesting">
+        <xsl:call-template name="programTable"/>
+        <xsl:apply-templates select="category"/>
+    </xsl:template>
+
+    <xsl:template match="category">
+        <h3>Category: <xsl:value-of select="@name"/></h3>
+        <xsl:call-template name="programTable"/>
+    </xsl:template>
+</xsl:stylesheet>
+
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml-nonwellformed.xsl b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml-nonwellformed.xsl
new file mode 100644 (file)
index 0000000..03d1908
--- /dev/null
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+<xsl:output method="xml"/>
+    <xsl:template match="report">
+        <html>
+            <head>
+                <title>KiSS crawler report</title>
+            </head>
+            <body>
+                <h1>KiSS crawler report</h1>
+                <xsl:apply-templates select="recorded"/>
+                <xsl:ifx test="count(interesting) > 0">
+                    <h2>Possibly interesting programs</h2>
+                    <xsl:apply-templates select="interesting"/>
+                </xsl:if>
+                <xsl:if test="count(//program) = 0">
+                    <xsl:text>No suitable programs found </xsl:text>
+                </xsl:if>
+            </body>
+        </html>
+
+    </xsl:template>
+
+    <xsl:template name="programTable">
+        <p>
+        <table align="left" cellpadding="5">
+            <!-- 
+            <tr align="left">
+                <th align="left">Time</th>
+                <th align="left">Channel</th>
+                <th align="left">Program</th>
+            </tr>
+            -->
+            <xsl:apply-templates select="program"/>
+        </table>
+        <br clear="left"/>
+        </p>
+    </xsl:template>
+
+    <xsl:template match="recorded">
+        <h2>
+            <xsl:choose>
+                <xsl:when test="@result = 'OK'">
+                    <xsl:text>Successfully recorded programs </xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'DUPLICATE'">
+                    <xsl:text>Already recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'CONFLICT'">
+                    <xsl:text>Conflicts with other recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result='ERROR'">
+                    <xsl:text>Programs that could not be recorded for
+                    technical reasons.</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+            </xsl:choose>
+        </h2>
+    </xsl:template>
+
+    <xsl:template name="addProgramInfo">
+        <tr align="left">
+            <td><xsl:value-of select="interval/begin"/> - <xsl:value-of select="interval/end"/>: <strong>
+                    <xsl:value-of select="name"/>
+                </strong> (<xsl:value-of select="channel"/>/<xsl:value-of select="keywords"/>)</td>
+
+        </tr>
+        <tr>
+            <td>
+                <blockquote>
+                        <font size="-1">
+                            <xsl:value-of select="description"/>
+                        </font>
+                </blockquote>
+            </td>
+
+
+        </tr>
+    </xsl:template>
+
+    <xsl:template match="program">
+        <xsl:call-template name="addProgramInfo"/>
+    </xsl:template>
+
+    <xsl:template match="interesting">
+        <xsl:call-template name="programTable"/>
+        <xsl:apply-templates select="category"/>
+    </xsl:template>
+
+    <xsl:template match="category">
+        <h3>Category: <xsl:value-of select="@name"/></h3>
+        <xsl:call-template name="programTable"/>
+    </xsl:template>
+</xsl:stylesheet>
+
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml.xsl b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml.xsl
new file mode 100644 (file)
index 0000000..ce113d5
--- /dev/null
@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+<xsl:output method="xml"/>
+    <xsl:template match="report">
+        <html>
+            <head>
+                <title>KiSS crawler report</title>
+            </head>
+            <body>
+                <h1>KiSS crawler report</h1>
+                <xsl:apply-templates select="recorded"/>
+                <xsl:if test="count(interesting) > 0">
+                    <h2>Possibly interesting programs</h2>
+                    <xsl:apply-templates select="interesting"/>
+                </xsl:if>
+                <xsl:if test="count(//program) = 0">
+                    <xsl:text>No suitable programs found </xsl:text>
+                </xsl:if>
+            </body>
+        </html>
+
+    </xsl:template>
+
+    <xsl:template name="programTable">
+        <p>
+        <table align="left" cellpadding="5">
+            <!-- 
+            <tr align="left">
+                <th align="left">Time</th>
+                <th align="left">Channel</th>
+                <th align="left">Program</th>
+            </tr>
+            -->
+            <xsl:apply-templates select="program"/>
+        </table>
+        <br clear="left"/>
+        </p>
+    </xsl:template>
+
+    <xsl:template match="recorded">
+        <h2>
+            <xsl:choose>
+                <xsl:when test="@result = 'OK'">
+                    <xsl:text>Successfully recorded programs </xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'DUPLICATE'">
+                    <xsl:text>Already recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'CONFLICT'">
+                    <xsl:text>Conflicts with other recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result='ERROR'">
+                    <xsl:text>Programs that could not be recorded for
+                    technical reasons.</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+            </xsl:choose>
+        </h2>
+    </xsl:template>
+
+    <xsl:template name="addProgramInfo">
+        <tr align="left">
+            <td><xsl:value-of select="interval/begin"/> - <xsl:value-of select="interval/end"/>: <strong>
+                    <xsl:value-of select="name"/>
+                </strong> (<xsl:value-of select="channel"/>/<xsl:value-of select="keywords"/>)</td>
+
+        </tr>
+        <tr>
+            <td>
+                <blockquote>
+                        <font size="-1">
+                            <xsl:value-of select="description"/>
+                        </font>
+                </blockquote>
+            </td>
+
+
+        </tr>
+    </xsl:template>
+
+    <xsl:template match="program">
+        <xsl:call-template name="addProgramInfo"/>
+    </xsl:template>
+
+    <xsl:template match="interesting">
+        <xsl:call-template name="programTable"/>
+        <xsl:apply-templates select="category"/>
+    </xsl:template>
+
+    <xsl:template match="category">
+        <h3>Category: <xsl:value-of select="@name"/></h3>
+        <xsl:call-template name="programTable"/>
+    </xsl:template>
+</xsl:stylesheet>
+
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml2.xsl b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToHtml2.xsl
new file mode 100644 (file)
index 0000000..2cec21f
--- /dev/null
@@ -0,0 +1,101 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+<xsl:include href="org/wamblee/xml/utilities.xsl"/>
+
+<xsl:output method="xml"/>
+    <xsl:template match="report">
+        <html>
+            <head>
+                <title>KiSS crawler report</title>
+            </head>
+            <body>
+                <h1>KiSS crawler report</h1>
+                <xsl:apply-templates select="recorded"/>
+                <xsl:if test="count(interesting) > 0">
+                    <h2>Possibly interesting programs</h2>
+                    <xsl:apply-templates select="interesting"/>
+                </xsl:if>
+                <xsl:if test="count(//program) = 0">
+                    <xsl:text>No suitable programs found </xsl:text>
+                </xsl:if>
+            </body>
+        </html>
+
+    </xsl:template>
+
+    <xsl:template name="programTable">
+        <p>
+        <table align="left" cellpadding="5">
+            <!-- 
+            <tr align="left">
+                <th align="left">Time</th>
+                <th align="left">Channel</th>
+                <th align="left">Program</th>
+            </tr>
+            -->
+            <xsl:apply-templates select="program"/>
+        </table>
+        <br clear="left"/>
+        </p>
+    </xsl:template>
+
+    <xsl:template match="recorded">
+        <h2>
+            <xsl:choose>
+                <xsl:when test="@result = 'OK'">
+                    <xsl:text>Successfully recorded programs </xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'DUPLICATE'">
+                    <xsl:text>Already recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result = 'CONFLICT'">
+                    <xsl:text>Conflicts with other recorded programs</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+                <xsl:when test="@result='ERROR'">
+                    <xsl:text>Programs that could not be recorded for
+                    technical reasons.</xsl:text>
+                    <xsl:call-template name="programTable"/>
+                </xsl:when>
+            </xsl:choose>
+        </h2>
+    </xsl:template>
+
+    <xsl:template name="addProgramInfo">
+        <tr align="left">
+            <td><xsl:value-of select="interval/begin"/> - <xsl:value-of select="interval/end"/>: <strong>
+                    <xsl:value-of select="name"/>
+                </strong> (<xsl:value-of select="channel"/>/<xsl:value-of select="keywords"/>)</td>
+
+        </tr>
+        <tr>
+            <td>
+                <blockquote>
+                        <font size="-1">
+                            <xsl:value-of select="description"/>
+                        </font>
+                </blockquote>
+            </td>
+
+
+        </tr>
+    </xsl:template>
+
+    <xsl:template match="program">
+        <xsl:call-template name="addProgramInfo"/>
+    </xsl:template>
+
+    <xsl:template match="interesting">
+        <xsl:call-template name="programTable"/>
+        <xsl:apply-templates select="category"/>
+    </xsl:template>
+
+    <xsl:template match="category">
+        <h3>Category: <xsl:value-of select="@name"/></h3>
+        <xsl:call-template name="programTable"/>
+    </xsl:template>
+</xsl:stylesheet>
+
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToText.xsl b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/reportToText.xsl
new file mode 100644 (file)
index 0000000..c1f7023
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+  <xsl:output method="text"/>
+  
+  <xsl:template match="report">
+     <xsl:text>Hello world!</xsl:text> 
+  </xsl:template>
+  
+</xsl:stylesheet>
diff --git a/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/utilities.xsl b/tags/wamblee-utils-0.2.1/support/general/src/test/resources/org/wamblee/xml/utilities.xsl
new file mode 100644 (file)
index 0000000..0dd7e62
--- /dev/null
@@ -0,0 +1,142 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!-- Note the declaration of the namespace for XInclude. -->
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
+  xmlns:xi="http://www.w3.org/2001/XInclude">
+
+
+  <xsl:variable name="newline">
+    <xsl:text>&#10;</xsl:text>
+  </xsl:variable>
+
+  <xsl:variable name="carriageReturn">
+    <xsl:text>&#13;&#10;</xsl:text>
+  </xsl:variable>
+
+  <!-- =====================================================
+    Replace one string by another
+    - src: string to do substituion in
+    - from: literal string to replace
+    - to:substitution string.
+    ======================================================-->
+  <xsl:template name="string-replace">
+    <xsl:param name="src"/>
+    <xsl:param name="from"/>
+    <xsl:param name="to"/>
+    <xsl:choose>
+      <xsl:when test="contains($src, $from)">
+        <xsl:value-of select="substring-before($src, $from)"/>
+        <xsl:value-of select="$to"/>
+        <xsl:call-template name="string-replace">
+          <xsl:with-param name="src" select="substring-after($src, $from)"/>
+          <xsl:with-param name="from" select="$from"/>
+          <xsl:with-param name="to" select="$to"/>
+        </xsl:call-template>
+      </xsl:when>
+      <xsl:otherwise>
+        <xsl:value-of select="$src"/>
+      </xsl:otherwise>
+    </xsl:choose>
+  </xsl:template>
+
+  <xsl:template name="indent">
+    <xsl:param name="src"/>
+    <xsl:param name="indentString"/>
+    <xsl:value-of select="$indentString"/>
+    <xsl:call-template name="string-replace">
+      <xsl:with-param name="src">
+        <xsl:value-of select="$src"/>
+      </xsl:with-param>
+      <xsl:with-param name="from">
+        <xsl:value-of select="$newline"/>
+      </xsl:with-param>
+      <xsl:with-param name="to">
+        <xsl:value-of select="$newline"/>
+        <xsl:value-of select="$indentString"/>
+      </xsl:with-param>
+    </xsl:call-template>
+  </xsl:template>
+
+  <xsl:template name="word-wrap">
+    <xsl:param name="src"/>
+    <xsl:param name="width"/>
+
+    <xsl:call-template name="word-wrap-impl">
+      <xsl:with-param name="src">
+        <xsl:call-template name="string-replace">
+          <xsl:with-param name="src">
+            <xsl:value-of select="$src"/>
+          </xsl:with-param>
+          <xsl:with-param name="from">
+            <xsl:text>  </xsl:text>
+          </xsl:with-param>
+          <xsl:with-param name="to">
+            <xsl:text> </xsl:text>
+          </xsl:with-param>
+        </xsl:call-template>
+      </xsl:with-param>
+      <xsl:with-param name="width">
+        <xsl:value-of select="$width"/>
+      </xsl:with-param>
+      <xsl:with-param name="index">
+        <xsl:value-of select="0"/>
+      </xsl:with-param>
+    </xsl:call-template>
+  </xsl:template>
+
+  <xsl:template name="word-wrap-impl">
+    <xsl:param name="src"/>
+    <xsl:param name="index"/>
+    <xsl:param name="width"/>
+
+    <xsl:variable name="word">
+      <xsl:value-of select="substring-before($src, ' ')"/>
+    </xsl:variable>
+    <xsl:variable name="wordlength">
+      <xsl:value-of select="string-length($word)"/>
+    </xsl:variable>
+    <xsl:variable name="remainder">
+      <xsl:value-of select="substring($src, $wordlength+2)"/>
+    </xsl:variable>
+
+    <xsl:choose>
+      <xsl:when test="$index + $wordlength + 1 &gt; $width">
+        <xsl:value-of select="$newline"/>
+        <xsl:value-of select="$word"/>
+        <xsl:text> </xsl:text>
+        <xsl:if test="string-length($remainder) > 0">
+          <xsl:call-template name="word-wrap-impl">
+            <xsl:with-param name="src">
+              <xsl:value-of select="$remainder"/>
+            </xsl:with-param>
+            <xsl:with-param name="index">
+              <xsl:value-of select="$wordlength + 1"/>
+            </xsl:with-param>
+            <xsl:with-param name="width">
+              <xsl:value-of select="$width"/>
+            </xsl:with-param>
+          </xsl:call-template>
+        </xsl:if>
+      </xsl:when>
+      <xsl:otherwise>
+        <xsl:value-of select="$word"/>
+        <xsl:text> </xsl:text>
+
+        <xsl:if test="string-length($remainder) > 0">
+          <xsl:call-template name="word-wrap-impl">
+            <xsl:with-param name="src">
+              <xsl:value-of select="$remainder"/>
+            </xsl:with-param>
+            <xsl:with-param name="index">
+              <xsl:value-of select="$index + $wordlength+1"/>
+            </xsl:with-param>
+            <xsl:with-param name="width">
+              <xsl:value-of select="$width"/>
+            </xsl:with-param>
+          </xsl:call-template>
+        </xsl:if>
+      </xsl:otherwise>
+    </xsl:choose>
+  </xsl:template>
+
+</xsl:stylesheet>
diff --git a/tags/wamblee-utils-0.2.1/support/pom.xml b/tags/wamblee-utils-0.2.1/support/pom.xml
new file mode 100644 (file)
index 0000000..2230475
--- /dev/null
@@ -0,0 +1,21 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-support</artifactId>
+  <packaging>pom</packaging>
+  <name>/support</name>
+  <url>http://wamblee.org</url>
+
+  <modules>
+    <module>general</module>
+    <module>spring</module>
+  </modules>
+  
+</project>
diff --git a/tags/wamblee-utils-0.2.1/support/spring/pom.xml b/tags/wamblee-utils-0.2.1/support/spring/pom.xml
new file mode 100644 (file)
index 0000000..5dfe1d4
--- /dev/null
@@ -0,0 +1,76 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-support-spring</artifactId>
+  <packaging>jar</packaging>
+  <name>/support/spring</name>
+  <url>http://wamblee.org</url>
+  <dependencies>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <version>0.2.1</version>
+      <type>test-jar</type>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-beans</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-hibernate3</artifactId>
+      <exclusions>
+        <exclusion>
+          <groupId>org.hibernate</groupId>
+          <artifactId>hibernate</artifactId>
+        </exclusion>
+      </exclusions>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-hibernate-jpa</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+       <dependency>
+      <groupId>org.springframework</groupId>
+      <artifactId>spring-aop</artifactId>
+    </dependency>
+    <!-- should be possible to remove the dependence on log4j -->
+    <dependency>
+      <groupId>log4j</groupId>
+      <artifactId>log4j</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>dom4j</groupId>
+      <artifactId>dom4j</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>net.sf.ehcache</groupId>
+      <artifactId>ehcache</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-hibernate-jpa</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>jaxen</groupId>
+      <artifactId>jaxen</artifactId>
+    </dependency>
+
+  </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java b/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java
new file mode 100644 (file)
index 0000000..61bd98a
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright 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.wamblee.concurrency.spring;
+
+import org.aopalliance.intercept.MethodInterceptor;
+import org.aopalliance.intercept.MethodInvocation;
+import org.wamblee.concurrency.Lock;
+
+/**
+ * Locking advice. This automatically synchronized an object using a given lock.  
+ *
+ * @author Erik Brakkee
+ */
+public class LockAdvice implements MethodInterceptor {
+    
+    /**
+     * Lock to use. 
+     */
+    private Lock _lock; 
+    
+    /**
+     * Constructs lock advice.  
+     * @param aLock Lock to use. 
+     */
+    public LockAdvice(Lock aLock) { 
+        _lock = aLock; 
+    }
+    
+    /* (non-Javadoc)
+     * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
+     */
+    public Object invoke(MethodInvocation aInvocation) throws Throwable {
+        _lock.acquire();
+        try {  
+            return aInvocation.proceed(); 
+        } finally { 
+            _lock.release();
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java b/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java
new file mode 100644 (file)
index 0000000..e01f086
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright 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.wamblee.general.spring;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.access.BeanFactoryLocator;
+import org.springframework.beans.factory.access.BeanFactoryReference;
+import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
+import org.wamblee.general.BeanFactory;
+import org.wamblee.general.BeanFactoryException;
+import org.wamblee.general.BeanKernel;
+
+/**
+ * Bean factory which uses Spring. This bean factory cannot be configured
+ * directly in the {@link org.wamblee.general.BeanKernel} because it does not
+ * provide a default no-arg constructor. Therefore, it must be delegated to or
+ * it must tbe subclassed to provide a default constructor.
+ */
+public class SpringBeanFactory implements BeanFactory {
+
+    private BeanFactoryReference _factoryReference;
+
+    /**
+     * Constructs the bean factory.
+     * 
+     * @param aSelector
+     *            Selector to find the appropriate bean ref context.
+     * @param aFactoryName
+     *            Spring bean factory to use.
+     */
+    public SpringBeanFactory(String aSelector, String aFactoryName) {
+        try {
+            BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator
+                    .getInstance(aSelector);
+            _factoryReference = locator.useBeanFactory(aFactoryName);
+        } catch (BeansException e) {
+            throw new BeanFactoryException(
+                    "Could not load bean factory: selector = '" + aSelector
+                            + "', factory = '" + aFactoryName + "'", e);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.general.BeanFactory#find(java.lang.String)
+     */
+    public Object find(String aId) {
+        return find(aId, Object.class);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.general.BeanFactory#find(java.lang.Class)
+     */
+    public <T> T find(Class<T> aClass) {
+        return find(aClass.getName(), aClass);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.general.BeanFactory#find(java.lang.String,
+     *      java.lang.Class)
+     */
+    public <T> T find(String aId, Class<T> aClass) {
+        try {
+            Object obj = _factoryReference.getFactory().getBean(aId, aClass);
+            assert obj != null;
+            return aClass.cast(obj);
+        } catch (BeansException e) {
+            throw new BeanFactoryException(e.getMessage(), e);
+        }
+    }
+    
+    /**
+     * Gets the spring bean factory. 
+     * @return Spring bean factory. 
+     */
+    public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() { 
+        return _factoryReference.getFactory(); 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java b/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java
new file mode 100644 (file)
index 0000000..003395d
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright 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.wamblee.persistence.hibernate;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+/**
+ * Hibernate mapping files to use. 
+ *
+ * @author Erik Brakkee
+ */
+public class HibernateMappingFiles extends ArrayList<String> {
+    
+    /**
+     * Constructs an empty list of hibernate mapping files. 
+     *
+     */
+    public HibernateMappingFiles() { 
+        super(); 
+    }
+    
+    /**
+     * Constructs the list of Spring config files. 
+     * @param aFiles Files. 
+     */
+    public HibernateMappingFiles(String[] aFiles) { 
+        super(); 
+        addAll(Arrays.asList(aFiles));
+    }
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java b/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java
new file mode 100644 (file)
index 0000000..8425fac
--- /dev/null
@@ -0,0 +1,281 @@
+/*
+ * Copyright 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.wamblee.persistence.hibernate;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
+import org.wamblee.persistence.Persistent;
+
+/**
+ * Extension of
+ * {@link org.springframework.orm.hibernate.support.HibernateDaoSupport}.
+ *
+ * @author Erik Brakkee
+ */
+public class HibernateSupport extends HibernateDaoSupport {
+
+    private static final Log LOG = LogFactory.getLog(HibernateSupport.class);
+
+    /**
+     * This class provided an equality operation based on the object reference
+     * of the wrapped object. This is required because we cannto assume that the
+     * equals operation has any meaning for different types of persistent
+     * objects. This allows us to use the standard collection classes for
+     * detecting cyclic dependences and avoiding recursion.
+     * 
+     */
+    private static final class ObjectElem {
+        private Object _object;
+
+        public ObjectElem(Object aObject) {
+            _object = aObject;
+        }
+
+        public boolean equals(Object aObj) {
+            return ((ObjectElem) aObj)._object == _object;
+        }
+
+        public int hashCode() {
+            return _object.hashCode();
+        }
+    }
+
+    /**
+     * Constructs the object.
+     * 
+     */
+    public HibernateSupport() {
+        // Empty
+    }
+
+    /**
+     * Performes a hibernate <code>Session.merge()</code> and updates the
+     * object with the correct primary key and version. This is an extension to
+     * the hibernate merge operation because hibernate itself leaves the object
+     * passed to merge untouched.
+     * 
+     * Use this method with extreme caution since it will recursively load all
+     * objects that the current object has relations with and for which
+     * cascade="merge" was specified in the Hibernate mapping file.
+     * 
+     * @param aPersistent
+     *            Object to merge.
+     */
+    public void merge(Persistent aPersistent) {
+        merge(getHibernateTemplate(), aPersistent);
+    }
+
+    /**
+     * As {@link #merge(Persistent)} but with a given template. This method can
+     * be accessed in a static way.
+     * 
+     * @param aTemplate
+     *            Hibernate template
+     * @param aPersistent
+     *            Object to merge.
+     */
+    public static void merge(HibernateTemplate aTemplate, Persistent aPersistent) {
+        Persistent merged = (Persistent) aTemplate.merge(aPersistent);
+        processPersistent(aPersistent, merged, new ArrayList<ObjectElem>());
+    }
+
+    /**
+     * Copies primary keys and version from the result of the merged to the
+     * object that was passed to the merge operation. It does this by traversing
+     * the properties of the object. It copies the primary key and version for
+     * objects that implement {@link Persistent} and applies the same rules to
+     * objects in maps and sets as well (i.e. recursively).
+     * 
+     * @param aPersistent
+     *            Object whose primary key and version are to be set.
+     * @param aMerged
+     *            Object that was the result of the merge.
+     * @param aProcessed
+     *            List of already processed Persistent objects of the persistent
+     *            part.
+     */
+    public static void processPersistent(Persistent aPersistent,
+            Persistent aMerged, List<ObjectElem> aProcessed) {
+        if (aPersistent == null && aMerged == null) {
+            return;
+        }
+        if (aPersistent == null || aMerged == null) {
+            throw new RuntimeException("persistent or merged object is null '"
+                    + aPersistent + "'" + "  '" + aMerged + "'");
+        }
+        ObjectElem elem = new ObjectElem(aPersistent);
+        if (aProcessed.contains(elem)) {
+            return; // already processed.
+        }
+        aProcessed.add(elem);
+
+        LOG.debug("Setting pk/version on " + aPersistent + " from " + aMerged);
+
+        if (aPersistent.getPrimaryKey() != null
+                && !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) {
+            LOG.error("Mismatch between primary key values: " + aPersistent
+                    + " " + aMerged);
+        } else {
+            aPersistent.setPersistedVersion(aMerged.getPersistedVersion());
+            aPersistent.setPrimaryKey(aMerged.getPrimaryKey());
+        }
+
+        Method[] methods = aPersistent.getClass().getMethods();
+        for (Method getter : methods) {
+            if (getter.getName().startsWith("get")) {
+                Class returnType = getter.getReturnType();
+
+                try {
+                    if (Set.class.isAssignableFrom(returnType)) {
+                        Set merged = (Set) getter.invoke(aMerged);
+                        Set persistent = (Set) getter.invoke(aPersistent);
+                        processSet(persistent, merged, aProcessed);
+                    } else if (List.class.isAssignableFrom(returnType)) {
+                        List merged = (List) getter.invoke(aMerged);
+                        List persistent = (List) getter.invoke(aPersistent);
+                        processList(persistent, merged, aProcessed);
+                    } else if (Map.class.isAssignableFrom(returnType)) {
+                        Map merged = (Map) getter.invoke(aMerged);
+                        Map persistent = (Map) getter.invoke(aPersistent);
+                        processMap(persistent, merged, aProcessed);
+                    } else if (Persistent.class.isAssignableFrom(returnType)) {
+                        Persistent merged = (Persistent) getter.invoke(aMerged);
+                        Persistent persistent = (Persistent) getter
+                                .invoke(aPersistent);
+                        processPersistent(persistent, merged, aProcessed);
+                    } else if (returnType.isArray()
+                            && Persistent.class.isAssignableFrom(returnType
+                                    .getComponentType())) {
+                        Persistent[] merged = (Persistent[]) getter
+                                .invoke(aMerged);
+                        Persistent[] persistent = (Persistent[]) getter
+                                .invoke(aPersistent);
+                        for (int i = 0; i < persistent.length; i++) {
+                            processPersistent(persistent[i], merged[i],
+                                    aProcessed);
+                        }
+                    }
+                } catch (InvocationTargetException e) {
+                    throw new RuntimeException(e.getMessage(), e);
+                } catch (IllegalAccessException e) {
+                    throw new RuntimeException(e.getMessage(), e);
+                }
+            }
+        }
+
+    }
+
+    /**
+     * Process the persistent objects in the collections.
+     * 
+     * @param aPersistent
+     *            Collection in the original object.
+     * @param aMerged
+     *            Collection as a result of the merge.
+     * @param aProcessed
+     *            List of processed persistent objects.
+     */
+    public static void processList(List aPersistent, List aMerged,
+            List<ObjectElem> aProcessed) {
+        Object[] merged = aMerged.toArray();
+        Object[] persistent = aPersistent.toArray();
+        if (merged.length != persistent.length) {
+            throw new RuntimeException("Array sizes differ " + merged.length
+                    + " " + persistent.length);
+        }
+        for (int i = 0; i < merged.length; i++) {
+            assert merged[i].equals(persistent[i]);
+            if (merged[i] instanceof Persistent) {
+                processPersistent((Persistent) persistent[i],
+                        (Persistent) merged[i], aProcessed);
+            }
+        }
+    }
+
+    /**
+     * Process the persistent objects in sets.
+     * 
+     * @param aPersistent
+     *            Collection in the original object.
+     * @param aMerged
+     *            Collection as a result of the merge.
+     * @param aProcessed
+     *            List of processed persistent objects.
+     */
+    public static void processSet(Set aPersistent, Set aMerged,
+            List<ObjectElem> aProcessed) {
+        if (aMerged.size() != aPersistent.size()) {
+            throw new RuntimeException("Array sizes differ " + aMerged.size()
+                    + " " + aPersistent.size());
+        }
+        for (Object merged : aMerged) {
+            // Find the object that equals the merged[i]
+            for (Object persistent : aPersistent) {
+                if (persistent.equals(merged)) {
+                    processPersistent((Persistent) persistent,
+                            (Persistent) merged, aProcessed);
+                    break;
+                }
+            }
+        }
+    }
+
+    /**
+     * Process the Map objects in the collections.
+     * 
+     * @param aPersistent
+     *            Collection in the original object.
+     * @param aMerged
+     *            Collection as a result of the merge.
+     * @param aProcessed
+     *            List of processed persistent objects.
+     */
+    public static void processMap(Map aPersistent, Map aMerged,
+            List<ObjectElem> aProcessed) {
+        if (aMerged.size() != aPersistent.size()) {
+            throw new RuntimeException("Sizes differ " + aMerged.size() + " "
+                    + aPersistent.size());
+        }
+        Set keys = aMerged.keySet();
+        for (Object key : keys) {
+            if (!aPersistent.containsKey(key)) {
+                throw new RuntimeException("Key '" + key + "' not found");
+            }
+            Object mergedValue = aMerged.get(key);
+            Object persistentValue = aPersistent.get(key);
+            if (mergedValue instanceof Persistent) {
+                if (persistentValue instanceof Persistent) {
+                    processPersistent((Persistent) persistentValue,
+                            (Persistent) mergedValue, aProcessed);
+                } else {
+                    throw new RuntimeException(
+                            "Value in original object is null, whereas merged object contains a value");
+                }
+            }
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/package.html b/tags/wamblee-utils-0.2.1/support/spring/src/main/java/org/wamblee/persistence/hibernate/package.html
new file mode 100644 (file)
index 0000000..6f14b9f
--- /dev/null
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+    wamblee.org
+</head>
+<body bgcolor="white">
+
+This package provides support utilities for persistence with hibernate.
+
+<!-- Put @see and @since tags down here. -->
+
+@since -
+
+</body>
+</html>
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java
new file mode 100644 (file)
index 0000000..b56beac
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright 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.wamblee.concurrency.spring;
+
+import org.springframework.aop.framework.ProxyFactoryBean;
+import org.wamblee.concurrency.AbstractLockTestCase;
+import org.wamblee.concurrency.JvmLock;
+import org.wamblee.concurrency.spring.LockAdvice;
+import org.wamblee.test.TimingUtils;
+
+/**
+ * 
+ *
+ * @author Erik Brakkee
+ */
+public class LockAdviceTest extends AbstractLockTestCase {
+
+    private class Runner implements Runnable {
+        public void run() {
+            LockAdviceTest.this.getTracker().eventOccurred(ACQUIRED);
+            TimingUtils.sleep(SLEEP_TIME);
+        }
+    }
+
+    private Runnable _target;
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.concurrency.AbstractLockTestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        
+        Runner runner = new Runner();
+        LockAdvice advice = new LockAdvice(new JvmLock());
+        
+        ProxyFactoryBean support = new ProxyFactoryBean();
+        support.setInterfaces(new Class[]{ Runnable.class });
+        support.setTarget(runner);
+        support.addAdvice(advice);
+        _target = (Runnable)support.getObject();
+        
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.wamblee.concurrency.AbstractLockTestCase#runThread()
+     */
+    @Override
+    protected Thread runThread() {
+        Thread t = new Thread(new Runnable() {
+            public void run() {
+                try {
+                    getTracker().eventOccurred(STARTED);
+                    _target.run();
+                    getTracker().eventOccurred(RELEASED);
+                } catch (Throwable e) {
+                    throw new RuntimeException(e);
+                }
+            };
+        });
+        t.start();
+        return t;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java
new file mode 100644 (file)
index 0000000..21bf195
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright 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.wamblee.general.spring;
+
+import org.wamblee.general.BeanFactoryException;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests the spring bean factory.
+ *
+ * @author Erik Brakkee
+ */
+public class SpringBeanFactoryTest extends TestCase {
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see junit.framework.TestCase#setUp()
+     */
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+    }
+
+    public void testExistingBeanRefContext() {
+        SpringBeanFactory factory = new SpringBeanFactory(
+                "org/wamblee/general/beanRefContext.xml", "test");
+
+        String value1 = factory.find(String.class);
+        assertEquals("hello", value1);
+        String value2 = (String) factory.find("java.lang.String");
+        assertEquals("hello", value2);
+        String value3 = factory.find("java.lang.String", String.class);
+        assertEquals("hello", value3);
+
+        try {
+            factory.find("unknown");
+        } catch (BeanFactoryException e) {
+            return; // ok
+        }
+        fail();
+    }
+
+    public void testUnknownBeanFactory() {
+        try {
+            new SpringBeanFactory(
+                    "org/wamblee/general/beanRefContext.xml", "unknown");
+        } catch (BeanFactoryException e) {
+            return; // ok
+        }
+        fail();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java
new file mode 100644 (file)
index 0000000..e5e566c
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.general.spring;
+
+/**
+ * Test bean factory.
+ *
+ * @author Erik Brakkee
+ */
+public class TestBeanFactory extends SpringBeanFactory {
+
+    
+    public TestBeanFactory() { 
+        super("org/wamblee/general/beanRefContext.xml", "test");
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java
new file mode 100644 (file)
index 0000000..aefe418
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright 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.wamblee.test.spring;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.hibernate.cfg.Configuration;
+import org.hibernate.tool.hbm2ddl.SchemaExport;
+
+/**
+ * Exporting the hibernate mapping. 
+ *
+ * @author Erik Brakkee
+ */
+public final class HibernateExporter {
+    
+    /**
+     * Disabled constructor.
+     *
+     */
+    private HibernateExporter() { 
+        // Empty
+    }
+    
+    public static void main(String[] aArgs) throws IOException {
+        String file = aArgs[0];
+        File dir = new File(aArgs[1]); 
+      
+        Configuration conf = HibernateUtils.getConfiguration(dir);
+        SchemaExport export = new SchemaExport(conf);
+        export.setDelimiter(";");
+        export.setOutputFile(file); 
+        export.create(true, false);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java
new file mode 100644 (file)
index 0000000..87219de
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 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.wamblee.test.spring;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.hibernate.cfg.Configuration;
+import org.hibernate.tool.hbm2ddl.SchemaUpdate;
+
+/**
+ * Exporting the hibernate mapping.
+ *
+ * @author Erik Brakkee
+ */
+public final class HibernateUpdater {
+    
+    /**
+     * Disabled constructor.
+     *
+     */
+    private HibernateUpdater() { 
+        // Empty
+    }
+
+    public static void main(String[] aArgs) throws IOException {
+        String file = aArgs[0];
+        File dir = new File(file);
+
+        Configuration conf = HibernateUtils.getConfiguration(dir);
+
+        SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf);
+        lSchemaUpdate.execute(true, true);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java
new file mode 100644 (file)
index 0000000..74a7ef7
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright 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.wamblee.test.spring;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+
+import org.apache.oro.io.AwkFilenameFilter;
+import org.hibernate.cfg.Configuration;
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.io.InputResource;
+
+/**
+ * Hibernate utilities.
+ *
+ * @author Erik Brakkee
+ */
+public final class HibernateUtils {
+
+    private static final String DATABASE_PROPS = "test.database.properties";
+
+    /**
+     * Disabled.
+     *
+     */
+    private HibernateUtils() { 
+        // Empty
+    }
+    
+    /**
+     * @param aDir
+     * @return
+     */
+    public static Configuration getConfiguration(File aDir) throws IOException {
+        Configuration conf = new Configuration();
+        File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter(
+                ".*\\.hbm\\.xml")));
+        for (File f : files) {
+            System.out.println("Mapping file: " + f);
+            conf.addFile(f);
+        }
+
+        Map<String, String> dbProps = getHibernateProperties();
+
+        for (Map.Entry<String, String> entry : dbProps.entrySet()) {
+            System.out.println("Property: " + entry.getKey() + "="
+                    + entry.getValue());
+            conf.setProperty(entry.getKey(), entry.getValue());
+        }
+
+        return conf;
+    }
+
+    private static Map<String, String> getHibernateProperties()
+            throws IOException {
+
+        System.out.println("Reading properties file: " + DATABASE_PROPS);
+        InputResource lPropFile = new ClassPathResource(DATABASE_PROPS);
+        Properties props = new Properties();
+        props.load(lPropFile.getInputStream());
+
+        Map<String, String> result = new TreeMap<String, String>();
+        result.put("hibernate.connection.driver_class", props
+                .getProperty("database.driver"));
+        result.put("hibernate.connection.url", props
+                .getProperty("database.url"));
+        result.put("hibernate.connection.username", props
+                .getProperty("database.username"));
+        result.put("hibernate.connection.password", props
+                .getProperty("database.password"));
+
+        return result;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java
new file mode 100644 (file)
index 0000000..a7cc6fe
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright 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.wamblee.test.spring;
+
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.wamblee.general.BeanFactory;
+import org.wamblee.general.BeanFactoryException;
+
+/**
+ * Bean factory which uses Spring. 
+ *
+ * @author Erik Brakkee
+ */
+public class TestSpringBeanFactory implements BeanFactory {
+    
+    private ApplicationContext _context; 
+    
+    public TestSpringBeanFactory(ApplicationContext aContext) {
+        _context = aContext; 
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.general.BeanFactory#find(java.lang.String)
+     */
+    public Object find(String aId) {
+       return find(aId, Object.class);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.general.BeanFactory#find(java.lang.Class)
+     */
+    public <T> T find(Class<T> aClass) {
+        return find(aClass.getName(), aClass);
+    }
+
+    /* (non-Javadoc)
+     * @see org.wamblee.general.BeanFactory#find(java.lang.String, java.lang.Class)
+     */
+    public <T> T find(String aId, Class<T> aClass) {
+        try {
+            Object obj = _context.getBean(aId, aClass);
+            assert obj != null; 
+            return aClass.cast(obj); 
+        } catch (BeansException e) { 
+            throw new BeanFactoryException(e.getMessage(), e);
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java
new file mode 100644 (file)
index 0000000..37ea898
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.test.spring;
+
+import java.util.Map;
+
+/**
+ * Transaction callback for testing. The test will fail if any type of exception
+ * is thrown.
+ *
+ * @author Erik Brakkee
+ */
+public interface TestTransactionCallback {
+    /**
+     * Executes code within a transaction, causing the testcase to fail if any
+     * type of exception is thrown.
+     * 
+     * @return A map containg the resuls of the execution. This is a convenient
+     *         method of returning multiple results from a call.
+     */
+    Map execute() throws Exception;
+}
diff --git a/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java b/tags/wamblee-utils-0.2.1/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java
new file mode 100644 (file)
index 0000000..a5011e4
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright 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.wamblee.test.spring;
+
+/**
+ * Transaction callback for testing. The test will fail if any type of exception
+ * is thrown.
+ *
+ * @author Erik Brakkee
+ */
+public interface TestTransactionCallbackWithoutResult {
+    /**
+     * Executes code within a transaction, causing the testcase to fail if any
+     * type of exception is thrown.
+     * 
+     */
+    void execute() throws Exception;
+}
diff --git a/tags/wamblee-utils-0.2.1/system/TODO.txt b/tags/wamblee-utils-0.2.1/system/TODO.txt
new file mode 100644 (file)
index 0000000..cac157b
--- /dev/null
@@ -0,0 +1,78 @@
+SetterConfiguration:
+- add type based removal of setters.
+- add values(Class aType) method for selecting a setter. 
+- add add(Class aType) method for selecting a type. 
+- verify that superclass setters are also taken into account.
+
+
+
+opzoeken waar de provided interfaces van de scope gebruikt worden, als het
+goed is nog nergens. Scope moet een Component worden en publiceren van een 
+interface leidt tot een nieuw provided interface.
+
+Component infrastructure
+* support simple component
+  - requires through constructor
+  - provides through getters
+* optional start and stop methods
+* giving names to a component must be optional
+* support for cached components and non-cached components.
+
+
+- Annotaties definieren
+
+
+@Component
+  class MyComponent {  
+
+  public MyComponent(Def aArg, Ghi aArg2) { 
+  }
+
+  @Provided(name = "name")
+  public Xyz getXyz();
+
+  @Start
+  public void myStart(); // Unlike the component
+}
+
+- Algemene classes maken die de constructor, start method, en 
+  methodes  identificeren om de component als Component te benaderen. 
+  in een object, samen met een wrapper die deze info gebruikt om het
+  object als Component te exportern. 
+  Er moet ook een wrapper zijn voor reeds geinstantieerde  objecten.
+
+- wrapper maken die geannoteerde classes interpreteert en via de eerdere
+  wrapper het object ontsluiten als component. 
+  Zowel geinstantieerde objecten als classes ondersteunen. 
+
+- add support for private setters.
+- add support or exposing provided services 
+  - superclass or interface of the concrete type instead of the concrete type
+    or not based on the concrete type at all. 
+  - based on getters. 
+- add support for field injection. 
+
+- add support for annotation based configuration instead of API-based
+
+- add support for type conversions. 
+
+- add support for multiplicity. 
+
+- add support for aggregating multiple servicss. 
+
+- add support for explicitly configuring which provided interface of 
+  a container is provided by which internal service. 
+
+- do not use equality but use logic for matching external required and
+  provided interfaces of a container. 
+
+  e.g. a service T provided by a container can be provided by a service 
+  U that provides subclasses of the provided interfaces of T
+
+  a service T required by a component inside a container is covered
+  by stronger requirements for subclasses of T. 
+
+- separate logic for connecting required and provided interfaces 
+  through a general graph model of the application. 
+  Then use generic filters, validations, and graph traversal APIs 
+  to implement the current functionality in the container. 
diff --git a/tags/wamblee-utils-0.2.1/system/general/pom.xml b/tags/wamblee-utils-0.2.1/system/general/pom.xml
new file mode 100644 (file)
index 0000000..5534dcb
--- /dev/null
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-system-general</artifactId>
+  <packaging>jar</packaging>
+  <name>/system/general</name>
+  <url>http://wamblee.org</url>
+  <dependencies>
+    <dependency>
+      <groupId>commons-logging</groupId>
+      <artifactId>commons-logging</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <type>test-jar</type>
+      <version>0.2.1</version>
+    </dependency>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java
new file mode 100644 (file)
index 0000000..ace1525
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * A Class Adapter adapts a given class to a Component.
+ *  
+ * @author Erik Brakkee
+ */
+public class ClassAdapter extends AbstractComponent<Object> {
+
+       private ClassConfiguration _classConfig;
+
+       public ClassAdapter(String aName, ClassConfiguration aClassConfig) {
+               super(aName, 
+                               aClassConfig.getProvidedInterfaces().toArray(new ProvidedInterface[0]),
+                               aClassConfig.getRequiredInterfaces().toArray(new RequiredInterface[0]));
+               _classConfig = aClassConfig; 
+       }
+       
+       @Override
+       protected Object doStart(Scope aScope) {
+               
+           Object obj =  _classConfig.create(aScope);
+           _classConfig.inject(aScope, obj);
+           
+           for (ProvidedInterface provided: getProvidedInterfaces()) { 
+               addInterface(provided, obj, aScope); 
+           }
+           
+           return obj;
+       }
+       
+       @Override
+       protected void doStop(Object aRuntime) {
+               // Empty. 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java
new file mode 100644 (file)
index 0000000..0fee7ac
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * The class configuration encapsulates the knowledge of how to wrap a class as a component.
+ * 
+ * @author Erik Brakkee
+ *
+ */
+public class ClassConfiguration {
+
+       private Class _class; 
+       private ConstructorConfiguration _constructorConfig;
+       private ObjectConfiguration _objectConfig; 
+       
+       /**
+        * Constructs the configuration. By default no constructor is selected and 
+        * one of {@link #select(Class...)} or 
+        * {@link #greedy()} must be called.  
+        * @param aClass Class to construct. 
+        */
+       public ClassConfiguration(Class aClass) {
+               _class = aClass; 
+               _constructorConfig = new ConstructorConfiguration(aClass);
+               _objectConfig = new ObjectConfiguration(aClass);
+       }
+       
+       public ConstructorConfiguration getConstructorConfig() {
+               return _constructorConfig;
+       }
+       
+       public ObjectConfiguration getObjectConfig() { 
+           return _objectConfig; 
+       }
+
+       /**
+        * Creates the object in the given scope. 
+        * @param aScope Scope containing required interfaces for this object. 
+        * @return object. 
+        */
+       public Object create(Scope aScope) {
+               return _constructorConfig.create(aScope);
+       }
+       
+       /**
+        * Injects required interfaces through the setters 
+        * @param aObject Object to inject into. 
+        * @param aScope Scope in which injection takes place. 
+        */
+       public void inject(Scope aScope, Object aObject) { 
+           _objectConfig.inject(aScope, aObject);
+       }
+       
+       public List<ProvidedInterface> getProvidedInterfaces() {
+           List<ProvidedInterface> result = new ArrayList<ProvidedInterface>();
+           result.add(new DefaultProvidedInterface("provided", _class));       
+           return result;
+       }
+       
+       public List<RequiredInterface> getRequiredInterfaces() { 
+           List<RequiredInterface> result = new ArrayList<RequiredInterface>();
+           result.addAll(_constructorConfig.getRequiredInterfaces());
+           result.addAll(_objectConfig.getRequiredInterfaces());
+           return result; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java
new file mode 100644 (file)
index 0000000..7a5c259
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.wamblee.collections.CollectionFilter;
+import org.wamblee.conditions.Condition;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.SystemAssemblyException;
+
+/**
+ * Class that allows configuration of the constructor to use. 
+ * 
+ * In particular, it provides:
+ * <ul>
+ *   <li> Selection of a constructor using explicit selection 
+ *      {@link #select(Class...)} or using the most greedy constructor 
+ *      {@link #greedy()}.
+ *   </li>
+ *   <li>
+ *      Selection of methods to invoke to inject other objects into the object.  
+ *   </li>
+ *   <li> Selection of fields to set. 
+ *   </li>
+ * </ul>
+ */
+public class ConstructorConfiguration {
+       private Class _class; 
+       private Constructor<?> _constructor;
+       private ParameterValues _values;
+       private boolean _publicOnly; 
+
+       /**
+        * Constructs the configuration. By default the public constructor with the 
+        * most arguments will be used.   
+        * @param aClass Class to construct. 
+        */
+       public ConstructorConfiguration(Class aClass) {
+               _class = aClass; 
+               _constructor = null;  
+               _publicOnly = true; 
+       }
+       
+       /**
+        * Sets whether or no non public constructors are also considered.
+        * Reset the choice of a constructor to its default.  
+        * @param aNonPublic
+        * @return
+        */
+       public ConstructorConfiguration setNonPublic(boolean aNonPublic) { 
+               _publicOnly = !aNonPublic;
+               _constructor = null;
+               _values = null;
+               return this; 
+       }
+       
+       /**
+        * Selects an explicit constructor.
+        * @param aTypes Arguments of the constructor.
+        * @return Return the injector to allow call chaining. 
+        */
+       public ConstructorConfiguration select(Class... aTypes) {
+               try {
+                       _constructor = _class.getDeclaredConstructor(aTypes); 
+               } catch (Exception e) {
+                       throw new SystemAssemblyException(e.getMessage(), e);
+               }
+               resetValues(); 
+               return this; 
+       }
+       
+       /**
+        * Selects the greediest constructor. 
+        * @return The injector to allow call chaining.
+        * @throws SystemAssemblyException if the greediest constructor cannot be uniquely 
+        *    identified.  
+        */
+       public ConstructorConfiguration greedy() { 
+               Constructor<?>[] declared = _class.getDeclaredConstructors();
+               if (declared.length == 0) {
+                       throw new SystemAssemblyException("Class '" + _class
+                                       + " is an interface, primitive type, or array");
+               }
+               int max = -1;
+               List<Constructor<?>> checked = new ArrayList<Constructor<?>>();
+               CollectionFilter.filter(Arrays.asList(declared), checked, 
+                       new Condition<Constructor<?>>() { 
+                       @Override
+                       public boolean matches(Constructor<?> aObject) {
+                               if ( !_publicOnly ) { 
+                                       return true; 
+                               } else { 
+                                       return Modifier.isPublic(aObject.getModifiers());
+                               }
+                       }
+               });
+               for (Constructor ctor : checked) {
+                       if (ctor.getParameterTypes().length > max) {
+                               max = ctor.getParameterTypes().length;
+                       }
+               }
+               final int max2 = max;
+               List<Constructor<?>> ctors = checked;
+               List<Constructor<?>> longest = new ArrayList<Constructor<?>>();
+               CollectionFilter.filter(ctors, longest,
+                               new Condition<Constructor<?>>() {
+                                       @Override
+                                       public boolean matches(Constructor<?> aObject) {
+                                               return aObject.getParameterTypes().length == max2;
+                                       }
+                               });
+               if (longest.size() > 1) {
+                       throw new SystemAssemblyException(
+                                       "Greediest constructor cannot be uniquely determined");
+               }
+           _constructor = longest.get(0);
+           resetValues();
+           return this; 
+       }
+       
+       public ParameterValues getParameters() {
+               getConstructor(); // initialize constructor if needed.
+               return _values; 
+       }
+
+       /**
+        * Resets the values. 
+        */
+       private void resetValues() {
+               _constructor.setAccessible(true);
+               _values = new ParameterValues(_constructor.getParameterTypes());        
+       }
+
+       /**
+        * Creates the object in the given scope. 
+        * @param aScope Scope containing required interfaces for this object. 
+        * @return object. 
+        */
+       public Object create(Scope aScope) {
+               Object[] values = _values.values(aScope);
+               try {
+                       return getConstructor().newInstance(values);
+               } catch (Exception e) {
+                       throw new SystemAssemblyException("Could not construct object "
+                                       + getConstructor() + " " + Arrays.asList(values), e);
+               }
+       }
+       
+       public List<RequiredInterface> getRequiredInterfaces() {
+               getConstructor(); // initialize constructor if needed.
+               return _values.getRequiredInterfaces(); 
+       }
+       
+       private Constructor getConstructor() { 
+               if (_constructor == null ) { 
+                       greedy(); 
+               }
+               return _constructor; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java
new file mode 100644 (file)
index 0000000..823b7c0
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.container.Container;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+
+public class DefaultContainer extends Container {
+
+    public DefaultContainer(String aName) {
+        super(aName);
+    }
+
+    @Override
+    public DefaultContainer addComponent(Component aComponent) {
+        super.addComponent(aComponent);
+        return this;
+    }
+    
+    public DefaultContainer addComponent(String aName, ClassConfiguration aConfiguration) {
+        return addComponent(new ClassAdapter(aName, aConfiguration));
+    }
+
+    public DefaultContainer addComponent(String aName, Object aObject, ObjectConfiguration aConfiguration) {
+        if ( !aConfiguration.appliesTo(aObject) ) { 
+            throw new IllegalArgumentException("Configuration '" + aConfiguration + "' does nto applu to '"  + 
+                    aObject + "'");
+        }
+        return addComponent(new ObjectAdapter(aName, aObject, aConfiguration));
+    }
+
+    
+    @Override
+    public DefaultContainer addRequiredInterface(RequiredInterface aRequired) {
+        super.addRequiredInterface(aRequired);
+        return this;
+    }
+
+    @Override
+    public DefaultContainer addProvidedInterface(ProvidedInterface aProvided) {
+        super.addProvidedInterface(aProvided);
+        return this;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java
new file mode 100644 (file)
index 0000000..98fa48a
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.Scope;
+
+/**
+ * Value provider that provides a fixed value.
+ *  
+ * @author Erik Brakkee
+ */
+class FixedValueProvider implements ValueProvider {
+       
+       private Object _value;
+       
+       /**
+        * Constructs the value. 
+        * @param aValue Value to construct. 
+        */
+       public FixedValueProvider(Object aValue) { 
+               _value = aValue; 
+       }
+
+       @Override
+       public Object getValue(Scope aScope) {
+               return _value; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java
new file mode 100644 (file)
index 0000000..ff2fa0a
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * An adapter class that adapts an existing object to a component. 
+ *  
+ * @author Erik Brakkee
+ */
+public class ObjectAdapter extends AbstractComponent<Object> {
+
+       private ObjectConfiguration _objectConfig;
+       private Object _object; 
+
+       public ObjectAdapter(String aName, Object aObject, ObjectConfiguration aObjectConfig) {
+               super(aName, 
+                               new ProvidedInterface[] { new DefaultProvidedInterface(aName, aObject.getClass()) },
+                               aObjectConfig.getRequiredInterfaces().toArray(new RequiredInterface[0]));
+               _objectConfig = aObjectConfig;
+               _object = aObject; 
+       }
+       
+       @Override
+       protected Object doStart(Scope aScope) {
+
+           _objectConfig.inject(aScope, _object);
+           
+           for (ProvidedInterface provided: getProvidedInterfaces()) { 
+               addInterface(provided, _object, aScope); 
+           }
+           
+           return _object; 
+       }
+       
+       @Override
+       protected void doStop(Object aRuntime) {
+               // Empty. 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java
new file mode 100644 (file)
index 0000000..22df049
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * General configuration for an instantiated object. 
+ * 
+ * @author Erik Brakkee
+ */
+public class ObjectConfiguration {
+    
+    private Class _class; 
+    private SetterConfiguration _setterConfig;
+
+    public ObjectConfiguration(Class aClass) { 
+        _class = aClass; 
+        _setterConfig = new SetterConfiguration(aClass);
+    }
+    
+    /**
+     * Performs injection into an object of the configured class
+     * using information from the given scope. 
+     * @param aScope Scope. 
+     * @param aObject Object. 
+     */
+    public void inject(Scope aScope, Object aObject) { 
+        _setterConfig.inject(aScope, aObject);
+    }
+    
+    public SetterConfiguration getSetterConfig() { 
+        return _setterConfig; 
+    }
+    
+    public List<RequiredInterface> getRequiredInterfaces() {
+        List<RequiredInterface> result = new ArrayList<RequiredInterface>();
+        result.addAll(_setterConfig.getRequiredInterfaces());
+        return result;    
+    }
+
+    public boolean appliesTo(Object aObject) {
+        return _class.isInstance(aObject);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java
new file mode 100644 (file)
index 0000000..1778981
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * Represents parameter values for a method or constructor and allows for the configuration
+ * of how these values are retrieved. 
+ * 
+ * @author Erik Brakkee
+ */
+public class ParameterValues {
+    private String[] _names; 
+       private Class[] _types;
+       private ValueProvider[] _values;
+
+       /**
+        * Constructs the configuration. By default no constructor is selected and 
+        * one of {@link #select(Class...)} or 
+        * {@link #greedy()} must be called.  
+        * @param aClass Class to construct. 
+        */
+       public ParameterValues(Class[] aTypes) {
+           _names = new String[aTypes.length];
+           for (int i = 0; i < aTypes.length; i++) { 
+               _names[i] = "arg" + i; 
+           }
+               _types = aTypes; 
+               resetValues();   
+       }
+       
+       /**
+     * Constructs the configuration. By default no constructor is selected and 
+     * one of {@link #select(Class...)} or 
+     * {@link #greedy()} must be called.
+     * @param aNames Names of the arguments.   
+     * @param aClass Class to construct. 
+     */
+    public ParameterValues(String[] aNames, Class[] aTypes) {
+        assert aNames.length == aTypes.length; 
+        _names = aNames;
+        _types = aTypes; 
+        resetValues();   
+    }
+       
+       /**
+        * The types of the parameter values. 
+        * @return Types. 
+        */
+       public Class[] getTypes() {
+               return _types;
+       }
+       
+       /**
+        * Sets argument i to be optional, meaning that null is allowed to be passed in.  
+        * @param aArg Argument to set.
+        */
+       public ParameterValues setOptional(int aArg) { 
+               _values[aArg] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
+                               "arg" + aArg, _types[aArg], true));
+               return this; 
+       }
+       
+       /**
+        * Sets the argument i to a fixed value.  
+        * @param aArg Argument to set. 
+        * @param aValue Value. 
+        */
+       public ParameterValues setValue(int aArg, Object aValue) { 
+               _values[aArg] = new FixedValueProvider(aValue);
+               return this; 
+       }
+       
+       /**
+        * Resets the values. 
+        */
+       private void resetValues() { 
+               _values = new ValueProvider[_types.length];
+               for (int i = 0; i < _values.length; i++) { 
+                       _values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface(
+                                       _names[i], _types[i]));
+               }
+       }
+       
+       /**
+        * Gets the required interfaces to provide values that are not provided
+        * in another way. 
+        * @return Required interfaces. 
+        */
+       public List<RequiredInterface> getRequiredInterfaces() { 
+               List<RequiredInterface> result = new ArrayList<RequiredInterface>(); 
+               for (ValueProvider provider: _values) { 
+                       if ( provider instanceof RequiredInterfaceProvider) { 
+                               result.add( ((RequiredInterfaceProvider)provider).getRequiredInterface());
+                       }
+               }
+               return result; 
+       }
+
+       /**
+        * Returns the values to use in the given scope. 
+        * @param aScope Scope within which to retrieve the values. 
+        * @return Values. 
+        */
+       public Object[] values(Scope aScope) {
+               Object[] values = new Object[_values.length];
+               for (int i = 0; i < _values.length; i++) {
+                       values[i] = _values[i].getValue(aScope);
+               }
+               return values; 
+       }
+       
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java
new file mode 100644 (file)
index 0000000..56170ae
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * Value provider that provides a value through a required interface.
+ *  
+ * @author Erik Brakkee
+ */
+class RequiredInterfaceProvider implements ValueProvider {
+       
+       private RequiredInterface _required; 
+       
+       /**
+        * Constructs the provider 
+        * @param aRequired Required interface. 
+        */
+       public RequiredInterfaceProvider(RequiredInterface aRequired) { 
+               _required = aRequired; 
+       }
+       
+       @Override
+       public Object getValue(Scope aScope) {
+               return aScope.getInterfaceImplementation(_required.getProvider(), Object.class);
+       }
+       
+       public RequiredInterface getRequiredInterface() {
+               return _required;
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java
new file mode 100644 (file)
index 0000000..57323a5
--- /dev/null
@@ -0,0 +1,303 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.awt.CompositeContext;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.wamblee.collections.CollectionFilter;
+import org.wamblee.conditions.Condition;
+import org.wamblee.conditions.FixedCondition;
+import org.wamblee.general.Pair;
+import org.wamblee.reflection.ReflectionUtils;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.SystemAssemblyException;
+
+/**
+ * Represents the configuration for exposing the setters of a class as required
+ * interfaces.
+ * 
+ * @author Erik Brakkee
+ */
+public class SetterConfiguration {
+
+       private Class _class;
+       private boolean _publicOnly;
+
+       private Map<Method, ParameterValues> _setters;
+
+       /**
+        * Constructs the setter configuration. By default no setters are added. 
+        * 
+        * @param aClass
+        *            Class which is being configured.
+        */
+       public SetterConfiguration(Class aClass) {
+               _class = aClass;
+               _publicOnly = true;
+               _setters = new HashMap<Method, ParameterValues>();
+       }
+
+       /**
+        * Makes sure that all available setters are used. 
+        */
+       public SetterConfiguration initAllSetters() {
+           _setters.clear();
+               for (Method method: getAllSetters(_class, _publicOnly) ) { 
+                       _setters.put(method, createParameterValues(method));
+               }
+               return this; 
+       }
+
+       /**
+        * Called to set whether non-public setters are also used. By default only
+        * public setters are used. The currently selected setters remain chosen.  
+        * 
+        * @param aIsNonPublic
+        *            Non public flag.
+        */
+       public SetterConfiguration setNonPublic(boolean aIsNonPublic) {
+               _publicOnly = !aIsNonPublic;
+               return this; 
+       }
+
+       /**
+        * Removes all setters.
+        * 
+        * @return Reference to the current object to allow call chaining.
+        */
+       public SetterConfiguration clear() {
+               _setters.clear();
+               return this;
+       }
+
+       /**
+        * Removes a setter from the set of methods.
+        * 
+        * @param aName
+        *            Name of the setter to remove.
+        * @return Reference to the current object to allow call chaining.
+        */
+       public SetterConfiguration remove(String aName) {
+               for (Method method : _setters.keySet()) {
+                       if (method.getName().equals(aName)) {
+                               _setters.remove(method);
+                               return this;
+                       }
+               }
+               throw new IllegalArgumentException(
+                               "No method configured by the name of '" + aName + "'");
+       }
+       
+       /**
+        * Removes the method from the set of methods. 
+        * @param aMethod Method to remove. 
+        * @return
+        */
+       public SetterConfiguration remove(Method aMethod) { 
+           if ( !aMethod.getDeclaringClass().isAssignableFrom(_class) ) { 
+               throw new RuntimeException("Method " + aMethod + " not found in class " + _class + " or its superclasses");
+           }
+           for (Method method : _setters.keySet()) {
+            if (method.equals(aMethod)) {
+                _setters.remove(method);
+                return this;
+            }
+        }
+        throw new IllegalArgumentException(
+                "Method '" + aMethod + "' was not configured. ");
+       }
+       
+       /**
+        * Adds a given setter name to the setters.
+        * 
+        * @param aName Name of a setter method.
+        * @return Reference to the current object to allow call chaining.
+        */
+       public SetterConfiguration add(final String aName) {
+               int oldlen = _setters.size();
+               List<Method> methods = new ArrayList<Method>();
+               CollectionFilter.filter(getAllSetters(_class, _publicOnly), methods,
+                               new Condition<Method>() {
+                                       @Override
+                                       public boolean matches(Method aObject) {
+                                               return aObject.getName().equals(aName);
+                                       }
+
+                               });
+               if (methods.size() == 0 ) {
+                       throw new IllegalArgumentException("Method '" + aName
+                                       + "' not found in " + _class.getName());
+               }
+               // TODO is it possible to get more than one setter here in case the subclass overrides
+               // the baseclass method? 
+               _setters.put(methods.get(0), createParameterValues(methods.get(0)));
+               return this;
+       }
+
+       /**
+        * Adds a given setter identified by the type it accepts to the list of
+        * setters.N
+        * 
+        * @param aType
+        *            Type to look for. Note that this must be the exact type as
+        *            autoboxing and autounboxing is not used.
+        * @return Reference to the current object to allow call chaining.
+        * @throws IllegalArgumentException
+        *             In case no setter is found or multiple setters are found.
+        */
+       public SetterConfiguration addSetter(final Class aType) {
+               List<Method> result = new ArrayList<Method>();
+               CollectionFilter.filter(getAllSetters(_class, _publicOnly), result,
+                               new Condition<Method>() {
+                                       @Override
+                                       public boolean matches(Method aObject) {
+                                               Class type = aObject.getParameterTypes()[0];
+                                               return type.equals(aType);
+                                       }
+
+                               });
+               if (result.size() == 0) {
+                       throw new IllegalArgumentException("No setter found in class '"
+                                       + _class.getName()
+                                       + "' that has a setter with argument type '"
+                                       + aType.getName() + "'");
+               }
+               if (result.size() > 1) {
+                       String setters = "";
+                       for (Method method : result) {
+                               setters += method.getName() + " ";
+                       }
+                       throw new IllegalArgumentException(
+                                       "Multiple setters found in class '" + _class.getName()
+                                                       + " that accept type '" + aType.getName() + "': "
+                                                       + setters);
+               }
+               Method method = result.get(0);
+               _setters.put(method, createParameterValues(method));
+               return this;
+       }
+
+       /**
+        * Gets all setters for the current class.
+        * 
+        * @return List of all setters.
+        */
+       public static List<Method> getAllSetters(Class aClass,
+                       boolean aPublicOnly) {
+               List<Method> result = new ArrayList<Method>();
+               for (Method method : getAllMethods(aClass)) {
+                       if (!aPublicOnly || Modifier.isPublic(method.getModifiers())) {
+                               if (method.getName().startsWith("set")
+                                               && method.getParameterTypes().length == 1) {
+                                       method.setAccessible(true);
+                                       result.add(method);
+                               }
+                       }
+               }
+               return result;
+       }
+
+       private static ParameterValues createParameterValues(Method aMethod) {
+           
+           Class[] paramTypes = aMethod.getParameterTypes();
+           String[] paramNames = new String[paramTypes.length];
+           for (int i = 0; i < paramTypes.length; i++) { 
+               paramNames[i] = aMethod.getName() + "." + i; 
+           } 
+               return new ParameterValues(paramNames, paramTypes);
+       }
+
+       private static final List<Method> getAllMethods(Class aClass) {
+               return ReflectionUtils.getAllMethods(aClass);
+       }
+
+       /**
+        * Gets the required interfaces based on the configured setteres.
+        * 
+        * @return List of required interfaces.
+        */
+       public List<RequiredInterface> getRequiredInterfaces() {
+               List<RequiredInterface> result = new ArrayList<RequiredInterface>();
+               for (Method method : _setters.keySet()) {
+                       result.addAll(_setters.get(method).getRequiredInterfaces());
+               }
+               return result;
+       }
+
+       /**
+        * Invokes all configured setters with the appropriate values.
+        * 
+        * @param aScope
+        *            Scope within which invocation takes place.
+        * @param aObject
+        *            Object on which the invocation takes place.
+        */
+       public void inject(Scope aScope, Object aObject) {
+               if (!_class.isInstance(aObject)) {
+                       throw new IllegalArgumentException("Object '" + aObject
+                                       + "' is not an instance of " + _class.getName());
+               }
+               for (Method method : _setters.keySet()) {
+                       ParameterValues values = _setters.get(method);
+
+                       try {
+                               method.invoke(aObject, values.values(aScope));
+                       } catch (IllegalAccessException e) {
+                               throw new SystemAssemblyException("Problem invoking " + method
+                                               + " with " + values, e);
+                       } catch (InvocationTargetException e) {
+                               throw new SystemAssemblyException("Problem invoking " + method
+                                               + " with " + values, e);
+                       }
+               }
+       }
+
+       /**
+        * Returns the parameter values for allowing detailed configuration of how
+        * parameter values are set.
+        * 
+        * @param aSetter
+        *            Setter name without the "set" prefix with the first character
+        *            converted to lower case.
+        * @return Parameter values.
+        */
+       public ParameterValues values(String aMethod) {
+               for (Method method : _setters.keySet()) {
+                       if (method.getName().equals(aMethod)) {
+                               return _setters.get(method);
+                       }
+               }
+               throw new IllegalArgumentException("No setter method '" + aMethod
+                               + "' found");
+       }
+
+       public List<Method> getSetters() { 
+               return new ArrayList<Method>(_setters.keySet());
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java
new file mode 100644 (file)
index 0000000..6582f8f
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.Scope;
+
+/**
+ * Interface used to provide values for arguments of methods and constructors. 
+ * 
+ * @author Erik Brakkee
+ */
+interface ValueProvider {
+
+       Object getValue(Scope aScope);
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/components/ORMappingConfig.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/components/ORMappingConfig.java
new file mode 100644 (file)
index 0000000..880e869
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright 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.wamblee.system.components;
+
+public class ORMappingConfig {
+
+    public enum DatabaseType {
+        MYSQL_INNO_DB, DERBY;
+
+        public static interface Switch<T> {
+            T handleMySqlInnoDb();
+
+            T handleDerby();
+        }
+
+        public <T> T handleCases(Switch<T> aSwitch) {
+
+            switch (this) {
+            case MYSQL_INNO_DB: {
+                return aSwitch.handleMySqlInnoDb();
+            }
+            case DERBY: {
+                return aSwitch.handleDerby();
+            }
+            default: {
+                throw new RuntimeException("Unhandled case " + this);
+            }
+            }
+        }
+    };
+
+    private boolean _schemaUpdate;
+    private DatabaseType _type;
+
+    public ORMappingConfig(boolean aSchemaUpdate, DatabaseType aType) {
+        _schemaUpdate = aSchemaUpdate;
+        _type = aType;
+    }
+
+    public boolean isSchemaUpdate() {
+        return _schemaUpdate;
+    }
+
+    public DatabaseType getType() {
+        return _type;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java
new file mode 100644 (file)
index 0000000..d3c7e07
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright 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.wamblee.system.components;
+
+import java.io.IOException;
+import java.util.Properties;
+
+import org.wamblee.io.InputResource;
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.Scope;
+
+/**
+ * Property component that reads a property file and provides
+ * it to other components through a provided interface.
+ * 
+ * NOTE: when multiple property components are used, disambiguation
+ * of provided and required interfaces is needed. 
+ *  
+ * @author Erik Brakkee
+ */
+public class PropertyComponent extends AbstractComponent<Properties> {
+    
+    private static ProvidedInterface PROPS = new DefaultProvidedInterface("props", Properties.class);
+    
+    private Properties _props;
+    
+    public PropertyComponent(String aName, InputResource aResource) throws IOException { 
+        this(aName, readProps(aResource)); 
+    }
+    
+    private static Properties readProps(InputResource aResource) throws IOException {
+        Properties props = new Properties(); 
+        props.load(aResource.getInputStream());
+        return props; 
+    }
+
+    public PropertyComponent(String aName, Properties aProps) {
+        super(aName);
+        _props = aProps; 
+        
+        addProvidedInterface(PROPS);
+    }
+
+    @Override
+    protected Properties doStart(Scope aScope) {
+        addInterface(PROPS, _props, aScope);
+        return _props; 
+    }
+
+    @Override
+    protected void doStop(Properties aRuntime) {
+        // Empty 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/container/Container.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/container/Container.java
new file mode 100644 (file)
index 0000000..9669cb2
--- /dev/null
@@ -0,0 +1,387 @@
+/*
+ * Copyright 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.wamblee.system.container;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wamblee.general.Pair;
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultScope;
+import org.wamblee.system.core.NamedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.system.graph.CompositeEdgeFilter;
+import org.wamblee.system.graph.component.ComponentGraph;
+import org.wamblee.system.graph.component.ConnectExternalProvidedProvidedFilter;
+import org.wamblee.system.graph.component.ConnectRequiredExternallyRequiredEdgeFilter;
+import org.wamblee.system.graph.component.ConnectRequiredProvidedEdgeFilter;
+
+/**
+ * Container consisting of multiple components.
+ * 
+ * @author Erik Brakkee
+ */
+public class Container extends AbstractComponent<Scope> {
+
+    private static final Log LOG = LogFactory.getLog(Container.class);
+
+    private List<Component> _components;
+    private CompositeEdgeFilter _edgeFilter; 
+    private boolean _sealed;
+
+    /**
+     * Constructs the container
+     * 
+     * @param aName
+     *            Name of the container
+     * @param aComponents
+     *            Components.
+     * @param aProvided
+     *            Provided services of the container
+     * @param aRequired
+     *            Required services by the container.
+     */
+    public Container(String aName, Component[] aComponents,
+            List<ProvidedInterface> aProvided, List<RequiredInterface> aRequired) {
+        super(aName, aProvided, aRequired);
+        _components = new ArrayList<Component>();
+
+        _edgeFilter = new CompositeEdgeFilter();
+        _sealed = false;
+        for (Component component : aComponents) {
+            addComponent(component);
+        }
+    }
+    
+    /**
+     * Constructs the container
+     * 
+     * @param aName
+     *            Name of the container
+     * @param aComponents
+     *            Components.
+     * @param aProvided
+     *            Provided services of the container
+     * @param aRequired
+     *            Required services by the container.
+     */
+    public Container(String aName, Component[] aComponents,
+            ProvidedInterface[] aProvided, RequiredInterface[] aRequired) {
+        this(aName, aComponents, Arrays.asList(aProvided), Arrays.asList(aRequired));
+    }
+
+    public Container(String aName) {
+        this(aName, new Component[0], new ProvidedInterface[0],
+                new RequiredInterface[0]);
+    }
+
+    public Container addComponent(Component aComponent) {
+        checkSealed();
+        if (aComponent.getContext() != null) {
+            throw new SystemAssemblyException(
+                    "Inconsistent hierarchy, component '"
+                            + aComponent.getName()
+                            + "' is already part of another hierarchy");
+        }
+        if ( findComponent(aComponent.getName()) != null ) {
+            throw new SystemAssemblyException("Duplicate component '"
+                    + aComponent.getName() + "'");
+        }
+        _components.add(aComponent);
+        aComponent.addContext(getQualifiedName());
+        return this;
+    }
+    
+    /**
+     * Explictly connects required and provided interfaces. 
+     * @param aClientComponent Client component, may not be null. 
+     * @param aRequiredInterface Required interface. If null it means all required interfaces. 
+     * @param aServerComponent Server component to connect to. If null, it means that no server components
+     *         may be connected to and the provider of the required interface will be null. 
+     * @param aProvidedInterface Provided interface. If null, it means that there is no restriction on the 
+     *   name of the provided interface and that it is automatically selected. 
+     */
+    public void connectRequiredProvided(String aClientComponent, String aRequiredInterface, 
+            String aServerComponent, String aProvidedInterface) {
+        checkSealed();
+        Component client = findComponent(aClientComponent);
+        Component server = findComponent(aServerComponent);
+        if ( client == null ) { 
+               throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aClientComponent + "' in the container");
+        }
+        if ( aRequiredInterface != null ) { 
+               if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) { 
+                       throw new SystemAssemblyException(
+                                       getQualifiedName() + ": Component '" + aClientComponent + "' does not have a required interface named '" 
+                                       + aRequiredInterface + "'");
+               }
+        }
+        if ( server == null ) { 
+               throw new SystemAssemblyException("No component '" + aClientComponent + "' in the container");
+        }
+        if ( aProvidedInterface != null ) { 
+               if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) { 
+                       throw new SystemAssemblyException(
+                                       getQualifiedName() + ": Component '" + aServerComponent + "' does not have a provided interface named '" 
+                                       + aProvidedInterface + "'");
+               }
+        }
+        _edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent, aRequiredInterface, aServerComponent, aProvidedInterface));
+    }
+    
+    /**
+     * Explicitly connects a externally required interface to an internally required interface. 
+     * @param aComponent Component requiring the interface (must be non-null). 
+     * @param aRequiredInterface Required interface of the component (must be non-null).
+     * @param aExternalRequiredInterface Externally required interface (must be non-null).
+     */
+    public void connectExternalRequired(String aComponent, String aRequiredInterface, 
+            String aExternalRequiredInterface) {
+        checkSealed();
+        Component client = findComponent(aComponent);
+        if ( client == null ) { 
+               throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aComponent + "' in the container");
+        }
+        if ( aRequiredInterface != null ) { 
+               if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) { 
+                       throw new SystemAssemblyException(
+                                       getQualifiedName() + ": Component '" + aComponent + "' does not have a required interface named '" 
+                                       + aRequiredInterface + "'");
+               }
+        }
+        if ( aExternalRequiredInterface != null) { 
+               if ( findInterface(getRequiredInterfaces(), aExternalRequiredInterface) == null ) { 
+                       throw new SystemAssemblyException(
+                                       getQualifiedName() + ": container does not have a required interface named '" 
+                                       + aExternalRequiredInterface + "'");
+               }
+        }
+        _edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter(
+                aComponent, aRequiredInterface, aExternalRequiredInterface));
+    }
+    
+    public void connectExternalProvided(String aExternalProvided, String aComponent, String aProvidedInterface) {
+        checkSealed();
+        Component server = findComponent(aComponent);
+       
+      
+        if ( server == null ) { 
+               throw new SystemAssemblyException("No component '" + aComponent + "' in the container");
+        }
+        if ( aProvidedInterface != null ) { 
+               if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) { 
+                       throw new SystemAssemblyException(
+                                       getQualifiedName() + ": Component '" + aComponent + "' does not have a provided interface named '" 
+                                       + aProvidedInterface + "'");
+               }
+        }
+        if ( aExternalProvided != null ) { 
+               if ( findInterface(getProvidedInterfaces(), aExternalProvided) == null) { 
+                       throw new SystemAssemblyException(
+                                       getQualifiedName() + ": Container does not have a provided interface named '" 
+                                       + aExternalProvided + "'");
+               }
+        }
+        _edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface));
+    }
+
+
+    @Override
+    public Container addProvidedInterface(ProvidedInterface aProvided) {
+        checkSealed();
+        super.addProvidedInterface(aProvided);
+        return this;
+    }
+
+    @Override
+    public Container addRequiredInterface(RequiredInterface aRequired) {
+        checkSealed();
+        super.addRequiredInterface(aRequired);
+        return this;
+    }
+
+    @Override
+    public void addContext(String aContext) {
+        super.addContext(aContext);
+        for (Component component : _components) {
+            component.addContext(aContext);
+        }
+    }
+
+    /**
+     * Validates the components together to check that there are no required
+     * services not in the required list and no services in the provided list
+     * that cannot be provided. Also logs a warning in case of superfluous
+     * requirements.
+     * 
+     * @throws SystemAssemblyException
+     *             in case of any validation problems.
+     */
+    public void validate() {
+        doStartOptionalDryRun(null, true);
+    }
+
+    /**
+     * Seal the container, meaning that no further components or interfaces may
+     * be added.
+     */
+    public void seal() {
+        _sealed = true;
+    }
+
+    /**
+     * Checks if the container is sealed.
+     * 
+     * @return True iff the container is sealed.
+     */
+    public boolean isSealed() {
+        return _sealed;
+    }
+
+    /**
+     * Utility method to start with an empty external scope. This is useful for
+     * top-level containers which are not part of another container.
+     * 
+     * @return Scope.
+     */
+    public Scope start() {
+        Scope scope = new DefaultScope(getProvidedInterfaces());
+        return super.start(scope);
+    }
+
+    @Override
+    protected Scope doStart(Scope aExternalScope) {
+        validate();
+        Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope);
+        ComponentGraph graph = doStartOptionalDryRun(scope, false);
+        exposeProvidedInterfaces(graph, aExternalScope, scope);
+        seal();
+        return scope;
+    }
+
+    private void exposeProvidedInterfaces(ComponentGraph aGraph, Scope aExternalScope,
+            Scope aInternalScope) {
+        for (Pair<ProvidedInterface,ProvidedInterface> mapping: 
+            aGraph.findExternalProvidedInterfaceMapping()) { 
+            Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class);
+            addInterface(mapping.getFirst(), svc, aExternalScope);
+        }
+    }
+
+    private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) {
+        ComponentGraph graph = createComponentGraph();
+        graph.validate();
+        graph.link();
+
+        LOG.info("Starting '" + getQualifiedName() + "'");
+
+        List<Component> started = new ArrayList<Component>();
+        for (Component component : _components) {
+            try {
+                // Start the service.
+                if (!aDryRun) {
+                    Object runtime = component.start(aScope);
+                    aScope.addRuntime(component, runtime);
+                    started.add(component);
+                }
+            } catch (SystemAssemblyException e) {
+                throw e;
+            } catch (RuntimeException e) {
+                LOG.error(getQualifiedName() + ": could not start '"
+                        + component.getQualifiedName() + "'", e);
+                stopAlreadyStartedComponents(started, aScope);
+                throw e;
+            }
+        }
+        return graph;
+    }
+
+    private ComponentGraph createComponentGraph() {
+        ComponentGraph graph = new ComponentGraph();
+        for (RequiredInterface req : getRequiredInterfaces()) {
+            graph.addRequiredInterface(this, req);
+        }
+        for (Component comp : _components) {
+            graph.addComponent(comp);
+        }
+        for (ProvidedInterface prov: getProvidedInterfaces()) { 
+            graph.addProvidedInterface(this, prov);
+        }
+
+        graph.addEdgeFilter(_edgeFilter);
+        return graph;
+    }
+
+    private void stopAlreadyStartedComponents(List<Component> aStarted,
+            Scope aScope) {
+        // an exception occurred, stop the successfully started
+        // components
+        for (int i = aStarted.size() - 1; i >= 0; i--) {
+            try {
+                Component component = aStarted.get(i);
+                aStarted.get(i).stop(aScope.getRuntime(component));
+            } catch (Throwable t) {
+                LOG.error(getQualifiedName() + ": error stopping "
+                        + aStarted.get(i).getQualifiedName());
+            }
+        }
+    }
+
+    @Override
+    protected void doStop(Scope aScope) {
+        for (int i = _components.size() - 1; i >= 0; i--) {
+            Component component = _components.get(i);
+            Object runtime = aScope.getRuntime(component);
+            component.stop(runtime);
+        }
+    }
+
+    private void checkSealed() {
+        if (_sealed) {
+            throw new SystemAssemblyException("Container is sealed");
+        }
+    }
+    
+    /**
+     * Finds a component based on the non-qualified name of the component. 
+     * @param aName Component name. 
+     * @return Component or null if not found. 
+     */
+    public Component findComponent(String aName) { 
+       for (Component<?> component: _components) { 
+               if ( component.getName().equals(aName)) { 
+                       return component; 
+               }
+       }
+       return null; 
+    }
+    
+    private static <T extends NamedInterface> T findInterface(List<T> aInterfaces, String aInterfaceName) { 
+       for (T intf: aInterfaces) { 
+               if ( intf.getName().equals(aInterfaceName)) { 
+                       return intf; 
+               }
+       }
+       return null; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java
new file mode 100644 (file)
index 0000000..d2cf69f
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Abstract subsystem class making it easy to implement new subsystems.
+ */
+public abstract class AbstractComponent<Type> implements Component<Type> {
+
+       private static final Log LOG = LogFactory.getLog(AbstractComponent.class);
+
+       private ThreadLocal<List<ProvidedInterface>> _remaining;
+
+       private String _context;
+       private String _name;
+       private List<ProvidedInterface> _provided;
+       private List<RequiredInterface> _required;
+
+       /**
+        * Constructs the subsystem.
+        * 
+        * @param aName
+        *            Name of the system.
+        * @param aProvided
+        *            Provided services.
+        * @param aRequired
+        *            Required services.
+        */
+       protected AbstractComponent(String aName, List<ProvidedInterface> aProvided,
+                       List<RequiredInterface> aRequired) {
+               _remaining = new ThreadLocal<List<ProvidedInterface>>();
+               _context = null;
+               _name = aName;
+               _provided = new ArrayList<ProvidedInterface>(aProvided);
+               _required = new ArrayList<RequiredInterface>(aRequired); 
+       }
+       
+       /**
+     * Constructs the subsystem.
+     * 
+     * @param aName
+     *            Name of the system.
+     * @param aProvided
+     *            Provided services.
+     * @param aRequired
+     *            Required services.
+     */
+    protected AbstractComponent(String aName, ProvidedInterface[] aProvided,
+            RequiredInterface[] aRequired) {
+        this(aName, Arrays.asList(aProvided), Arrays.asList(aRequired));
+    }
+       
+       protected AbstractComponent(String aName) {
+               this(aName, new ProvidedInterface[0], new RequiredInterface[0]);
+       }
+       
+       public AbstractComponent<Type> addProvidedInterface(ProvidedInterface aProvided) { 
+               _provided.add(aProvided);
+               return this; 
+       }
+       
+       public AbstractComponent<Type> addRequiredInterface(RequiredInterface aRequired) { 
+               _required.add(aRequired);
+               return this;
+       }
+       
+       @Override
+       public final String getName() {
+               return _name;
+       }
+
+       @Override
+       public void addContext(String aContext) {
+               if (_context == null) {
+                       _context = aContext;
+               } else {
+                       _context = aContext + "." + _context;
+               }
+       }
+       
+       @Override
+       public String getContext() {
+               return _context;
+       }
+
+       @Override
+       public String getQualifiedName() {
+               if (_context == null) {
+                       return getName();
+               }
+               return _context + "." + getName();
+       }
+
+       @Override
+       public final List<ProvidedInterface> getProvidedInterfaces() {
+               return Collections.unmodifiableList(_provided);
+       }
+
+       @Override
+       public final List<RequiredInterface> getRequiredInterfaces() {
+               return Collections.unmodifiableList(_required);
+       }
+
+       @Override
+       public final Type start(Scope aScope) {
+               LOG.info("Initialization starting '" + getQualifiedName() + "'");
+               List<ProvidedInterface> oldRemaining = _remaining.get();
+               _remaining.set(new ArrayList<ProvidedInterface>(getProvidedInterfaces()));
+               try {
+                       Type runtime = doStart(aScope);
+                       checkNotStartedInterfaces();
+                       LOG.info("Initialization finished '" + getQualifiedName() + "'");
+                       return runtime;
+               } finally {
+                       _remaining.set(oldRemaining);
+               }
+       }
+
+       private void checkNotStartedInterfaces() {
+               if (_remaining.get().size() > 0) {
+                       String notProvided = "";
+                       for (ProvidedInterface provided : _remaining.get()) {
+                               notProvided += "\nComponent " + getQualifiedName()
+                                               + " did not start interface " + provided;
+                       }
+                       throw new SystemAssemblyException(notProvided);
+               }
+       }
+
+       /**
+        * Must be implemented for initializing the subsystem. The implementation
+        * must call {@link #addInterface(ProvidedInterface, Object, Scope)} for each service that is started.
+        * 
+        * @return Returns the runtime of the component.
+        */
+       protected abstract Type doStart(Scope aScope);
+
+       /**
+        * Implementations must call this method to indicate that a new service has
+        * been started.
+        * 
+        * @param aDescriptor
+        *            Provided interface.
+        * @param aService
+        *            Implementation of the interface.
+        * @param aScope
+        *            scope in which to publish the implementation.
+        */
+       protected final void addInterface(ProvidedInterface aDescriptor,
+                       Object aService, Scope aScope) {
+               LOG.info("Interface '" + getQualifiedName() + "."
+                               + aDescriptor.getName() + "' started.");
+               if ( !_remaining.get().remove(aDescriptor) ) { 
+                   throw new SystemAssemblyException("Component '" + getQualifiedName() + "' started an unexpected interface '" + 
+                           aDescriptor + "' that was not registerd as a provided interface before");
+               }
+               aScope.publishInterface(aDescriptor, aService);
+       }
+
+       @Override
+       public void stop(Type aRuntime) {
+           LOG.info("Stopping initiated '" + getQualifiedName() + "'");
+               doStop(aRuntime);
+               LOG.info("Stopping completed '" + getQualifiedName() + "'");
+       }
+
+       protected abstract void doStop(Type aRuntime);
+
+       @Override
+       public String toString() {
+               return getQualifiedName();
+       }
+       
+       public ProvidedInterface findProvidedInterface(String aName) { 
+           for (ProvidedInterface provided: getProvidedInterfaces()) { 
+               if ( provided.getName().equals(aName)) { 
+                   return provided; 
+               }
+           }
+           return null; 
+       }
+       
+       public RequiredInterface findRequiredInterface(String aName) { 
+           for (RequiredInterface required: getRequiredInterfaces()) { 
+               if ( required.getName().equals(aName)) { 
+                   return required; 
+               }
+           }
+           return null; 
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/Component.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/Component.java
new file mode 100644 (file)
index 0000000..9506bb1
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.List;
+
+/**
+ * A component represents a part of a system that requires a 
+ * number of interfaces and provides a number of interfaces.
+ * 
+ * The component interface provides the meta-data for a component. 
+ * After calling {@link #start(Scope)}, an actual runtime representation of the
+ * component can be created which is independent of this component. 
+ * As a special case, the runtime representation may be identical to the 
+ * component instance but in general it is not. This allows a component to be 
+ * used as a factory for creating objects. 
+ * 
+ *
+ * @author Erik Brakkee
+ */
+public interface Component<Type> {
+       
+       /**
+        * Gets the name of the subsystem.
+        * @return Subsystem name. 
+        */
+       String getName();
+       
+       /**
+        * Prepends the context with a super context. 
+        */
+       void addContext(String aContext);
+       
+       /**
+        * Getst the context.
+        * @return Context or null if not set. 
+        */
+       String getContext();
+       
+       /**
+        * Gets the fully qualified name of the component which includes
+        * the context of the component.  
+        * This method can only be used after the component has started.
+        * @return Qualified name. 
+        */
+       String getQualifiedName(); 
+
+       /**
+        * Gets a description of the provided interfaces. 
+        * @return Provided interfaces. 
+        */
+       List<ProvidedInterface> getProvidedInterfaces();
+       
+       /**
+        * Gets a description of the required interfaces. 
+        * @return Required interfaces. 
+        */
+       List<RequiredInterface> getRequiredInterfaces();
+
+       
+       /**
+        * Initialises the subsystem by starting all the services that
+        * it described as provided.
+        * @param aScope Scope with external interface implementations that are available. The component 
+        *  must publish its runtime and its provided interfaces in this scope. 
+        * @return Gets an object representing the runtime of the component.  
+        */
+       Type start(Scope aScope);
+       
+       /**
+        * Stops a component. 
+        * @param aRuntime THe runtime part of the component.  
+        */
+       void stop(Type aRuntime); 
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java
new file mode 100644 (file)
index 0000000..c790567
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+
+/**
+ * Default implementation of a service descriptor.
+ *
+ * @author Erik Brakkee
+ */
+public class DefaultProvidedInterface implements ProvidedInterface {
+       
+       private String _name; 
+       private Class[] _interfaces;
+       
+       /**
+        * Constructs the descriptor. 
+        * @param aInterface Type of service. 
+        */
+       public DefaultProvidedInterface(String aName, Class aInterface) {
+               this(aName, new Class[] { aInterface }); 
+       }
+       
+       public DefaultProvidedInterface(String aName, Class[] aInterfaces) { 
+               _name = aName; 
+               _interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length); 
+       }
+
+       @Override
+       public String getName() {
+               return _name;
+       }
+       
+       @Override
+       public Class[] getInterfaceTypes() {
+               return _interfaces;
+       }
+       
+       @Override
+       public String toString() {
+               StringBuffer buf = new StringBuffer();
+               buf.append(getName());
+               buf.append(":");
+               for (Class intf: _interfaces) { 
+                       buf.append(" " + intf.getName());
+               }
+               return buf.toString();
+       }
+       
+       @Override
+       public boolean equals(Object aObj) {
+           return this == aObj;
+           /*
+           if ( !(aObj instanceof DefaultProvidedInterface)) { 
+               return false; 
+           }
+           DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj; 
+           return getEqualsRepresentation().equals(provided.getEqualsRepresentation());
+           */
+       }
+       
+       @Override
+       public int hashCode() {
+           return getEqualsRepresentation().hashCode();
+       }
+       
+       @Override
+       public boolean covers(ProvidedInterface aInterface) {
+           // TODO do more than just equals. 
+           if ( !(aInterface instanceof DefaultProvidedInterface)) { 
+               return false; 
+           }
+           return getEqualsRepresentation().equals(((DefaultProvidedInterface)aInterface).getEqualsRepresentation());
+       }
+       
+       
+       private String getEqualsRepresentation() { 
+           List<String> result = new ArrayList<String>(); 
+           for (Class cls: _interfaces) { 
+               result.add(cls.getName());
+           }
+           Collections.sort(result); 
+           String value = ""; 
+           for (String str: result) { 
+               value += ":" + str; 
+           }
+           return value; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java
new file mode 100644 (file)
index 0000000..4e0db74
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.Arrays;
+
+import org.wamblee.reflection.ReflectionUtils;
+
+public class DefaultRequiredInterface implements RequiredInterface {
+
+       private String _name;
+       private boolean _optional; 
+       private Class[] _required;
+       private ProvidedInterface _provider; 
+       
+       public DefaultRequiredInterface(String aName, Class aInterface) {
+               this(aName, new Class[] { aInterface }); 
+       }
+
+       public DefaultRequiredInterface(String aName, Class[] aInterfaces) {
+               this(aName, aInterfaces, false); 
+       }
+       
+       public DefaultRequiredInterface(String aName, Class aInterface, boolean aIsOptional) {
+           this(aName, new Class[] { aInterface }, aIsOptional );
+       }
+
+       
+       public DefaultRequiredInterface(String aName, Class[] aInterfaces, boolean aIsOptional) {
+               _name = aName; 
+               _optional = aIsOptional; 
+               _required = aInterfaces; 
+       }
+
+       @Override
+       public String getName() {
+               return _name;
+       }
+       
+       @Override
+       public boolean isOptional() {
+               return _optional; 
+       }
+       
+       @Override
+       public boolean implementedBy(ProvidedInterface aDescriptor) {
+               Class[] provided = aDescriptor.getInterfaceTypes();
+               for (Class required : _required) {
+                       if ( !serviceProvided(required, provided)) { 
+                               return false; 
+                       }
+               }
+               // all required interfaces are provided.
+               return true; 
+       }
+       
+       /**
+        * Check if the required interface is implemented by one of the provided interfaces. 
+        * @param aRequired required interface
+        * @param aProvided Provided interfaces.
+        * @return
+        */
+       private boolean serviceProvided(Class aRequired, Class[] aProvided) { 
+               for (Class provided: aProvided) {
+                       try {
+                               provided = ReflectionUtils.wrapIfNeeded(provided);
+                               aRequired = ReflectionUtils.wrapIfNeeded(aRequired);
+                               provided.asSubclass(aRequired);
+                               return true; 
+                       } catch (ClassCastException e) {
+                               // No match, try the next one.
+                       }
+               }
+               return false; 
+       }
+       
+       @Override
+       public ProvidedInterface getProvider() {
+               return _provider; 
+       }
+       
+       @Override
+       public void setProvider(ProvidedInterface aProvider) {
+           assert aProvider != null; 
+           assert implementedBy(aProvider);
+               _provider = aProvider;  
+       }
+       
+       @Override
+       public boolean equals(Object obj) { 
+           return this == obj; 
+       }
+       
+       @Override
+       public boolean covers(RequiredInterface obj) {
+           // TODO do more than equals. 
+               if ( !(obj instanceof DefaultRequiredInterface)) { 
+                       return false; 
+               }
+               DefaultRequiredInterface descr = (DefaultRequiredInterface)obj;
+               if ( _required.length != descr._required.length ) { 
+                       return false; 
+               }
+               String[] interfaces1 = new String[_required.length];
+               String[] interfaces2 = new String[_required.length];
+               for (int i = 0; i < _required.length; i++) {  
+                       interfaces1[i] = _required[i].getName();
+                       interfaces2[i] = descr._required[i].getName();
+               }
+               Arrays.sort(interfaces1);
+               Arrays.sort(interfaces2);
+               return Arrays.equals(interfaces1, interfaces2);
+       }
+
+       @Override
+       public int hashCode() {
+               return _required.hashCode(); 
+       }
+       
+       @Override
+       public String toString() {
+               StringBuffer buf = new StringBuffer();
+               buf.append("." + getName() + ":");
+               for (Class intf: _required) { 
+                       buf.append("." + intf.getName());
+               }
+               return buf.toString();
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java
new file mode 100644 (file)
index 0000000..50c6cc3
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class DefaultScope implements Scope {
+
+       private List<Scope> _parents;
+       private Map<String, Object> _properties;
+       private Map<String, Object> _runtimes;
+       private Map<ProvidedInterface, ProvidedInterfaceImplementation> _provided;
+       private List<ProvidedInterface> _externallyProvided;
+       
+       public DefaultScope(List<ProvidedInterface>aExternallyProvided) { 
+           this(aExternallyProvided.toArray(new ProvidedInterface[0]));
+       }
+
+       public DefaultScope(ProvidedInterface[] aExternallyProvided) {
+               this(aExternallyProvided, new ArrayList<Scope>());
+       }
+
+       public DefaultScope(ProvidedInterface[] aExternallyProvided, Scope aParent) {
+               this(aExternallyProvided, Arrays.asList(new Scope[] { aParent }));
+       }
+
+       public DefaultScope(ProvidedInterface[] aExternallyProvided,
+                       List<Scope> aParent) {
+               _parents = new ArrayList<Scope>(aParent);
+               _properties = new HashMap<String, Object>();
+               _runtimes = new HashMap<String, Object>();
+               _provided = new HashMap<ProvidedInterface, ProvidedInterfaceImplementation>();
+               _externallyProvided = new ArrayList<ProvidedInterface>(); 
+               _externallyProvided.addAll(Arrays.asList(aExternallyProvided));
+       }
+
+       @Override
+       public List<ProvidedInterface> getProvidedInterfaces() {
+               return Collections.unmodifiableList(_externallyProvided);
+       }
+
+       @Override
+       public Object get(String aKey) {
+               return _properties.get(aKey);
+       }
+
+       @Override
+       public void put(String aKey, Object aValue) {
+               _properties.put(aKey, aValue);
+       }
+
+       @Override
+       public void addRuntime(Component aComponent, Object aRuntime) {
+               _runtimes.put(aComponent.getName(), aRuntime);
+       }
+
+       @Override
+       public Object getRuntime(Component aComponent) {
+               return _runtimes.get(aComponent.getName());
+       }
+       
+       @Override
+       public Object getRuntime(String aName) {
+           return _runtimes.get(aName);
+       }
+
+       @Override
+       synchronized public void publishInterface(ProvidedInterface aInterface,
+                       Object aImplementation) {
+               _provided.put(aInterface, new ProvidedInterfaceImplementation(aInterface,
+                               aImplementation));
+       }
+
+       @Override
+       public <T> T getInterfaceImplementation(ProvidedInterface aInterface,
+                       Class<T> aType) {
+               if ( aInterface == null ) { 
+                       return null; 
+               } 
+               ProvidedInterfaceImplementation provided = _provided.get(aInterface);
+               if (provided == null) {
+                       for (Scope parent : _parents) {
+                               T impl = parent.getInterfaceImplementation(aInterface, aType);
+                               if ( impl != null ) { 
+                                       return impl; 
+                               }
+                       }
+                       return null; 
+               } else {
+                       return provided.getImplementation(aType);
+               }
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java
new file mode 100644 (file)
index 0000000..9800621
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+public interface NamedInterface {
+    /**
+     * Name for the interface. 
+     */
+    String getName();
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java
new file mode 100644 (file)
index 0000000..f09a527
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.Collection;
+
+/**
+ * Represents an interface provided by a component.
+ * Different component objects should never share ProvidedInterface instances!
+ *  
+ * @author Erik Brakkee
+ */
+public interface ProvidedInterface extends NamedInterface {
+       
+       /**
+        * Returns the service type. 
+        * @return Service type. 
+        */
+       Class[] getInterfaceTypes();
+       
+       
+       /**
+        * Determines whether the current provided interface exceeds the given provided interface. 
+        * In other words if it can provide at least what the given provided interface can provide. 
+        * @param aInterface Interface to compare to. 
+        * @return True if the current interface exceeds the given provided interface. 
+        */
+       boolean covers(ProvidedInterface aInterface); 
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java
new file mode 100644 (file)
index 0000000..abeb70d
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+/**
+ * Represents a provided interface together with its implementation. 
+ * 
+ * @author Erik Brakkee
+ */
+class ProvidedInterfaceImplementation {
+
+       private ProvidedInterface _provided; 
+       private Object _implementation; 
+       
+       /**
+        * Constructs the object. 
+        * @param aProvided Provided interface. 
+        * @param aImplementation Implementation. 
+        */
+       public ProvidedInterfaceImplementation(ProvidedInterface aProvided, Object aImplementation) { 
+               _provided = aProvided; 
+               _implementation = aImplementation; 
+       }
+
+       /**
+        * @return The provided interface.
+        */
+       public ProvidedInterface getProvided() {
+               return _provided;
+       }
+       
+       /**
+        * @param <T> Expected type of the implementation. 
+        * @param aType Type of the implementation. 
+        * @return Implementation. 
+        */
+       public <T> T getImplementation(Class<T> aType) {
+               return (T)_implementation;
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java
new file mode 100644 (file)
index 0000000..4dd77fc
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+public interface RequiredInterface extends NamedInterface {
+       
+       /**
+        * @return True iff the required interface is optional. 
+        */
+       boolean isOptional(); 
+       
+       
+       /**
+        * Checks if the service is provided by a given provided interface. 
+        * @param aInterface Provided interface. 
+        * @return
+        */
+       boolean implementedBy(ProvidedInterface aInterface);
+       
+       /**
+        * Sets the provider of this interface. 
+        * @param aProvider Provider. 
+        */
+       void setProvider(ProvidedInterface aProvider);
+       
+       /**
+        * Gets the provider interface. 
+        * @return Provider or null if not set. 
+        */
+       ProvidedInterface getProvider();
+       
+       /**
+        * Determines if the requirements of the current interface are at least those
+        * of the given required interface. 
+        */
+       boolean covers(RequiredInterface aInterface); 
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/Scope.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/Scope.java
new file mode 100644 (file)
index 0000000..fe83e85
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.List;
+
+/**
+ * A scope represents a set of running services and the runtime information for the 
+ * started components and is (usually) the result of 
+ * starting a container. 
+ * 
+ * @author Erik Brakkee
+ */
+public interface Scope {
+       
+       /**
+        * Gets the provided interfaces by this scope. 
+        * @return Provided interfaces. 
+        */
+       List<ProvidedInterface> getProvidedInterfaces();
+       
+       /**
+        * Adds a key value pair to the scope. 
+        * @param aKey Key 
+        * @param aValue Value. 
+        */
+       void put(String aKey, Object aValue); 
+       
+       /**
+        * Retrieves a value for the key. 
+        * @param aKey Key.
+        * @return Value. 
+        */
+       Object get(String aKey);
+       
+       /**
+        * Adds the runtime of a started component. 
+        * @param aComponent Component. 
+        * @param aRuntime Runtime. 
+        */
+       void addRuntime(Component aComponent, Object aRuntime);
+       
+       /**
+        * Publishes an implementation of a provided interface. 
+        * @param aInterface Interface that is provided.
+        * @param aImplementation Implementation of the interface.  
+        */
+       void publishInterface(ProvidedInterface aInterface, Object aImplementation); 
+       
+       /**
+        * Retrieves an implementation of a provided interface. 
+        * @param aProvided P
+        * rovided interface. If it is null then null is returned.  
+        * @param aType Type of implementation that is expected.
+        * @return Retrieved interface.
+        */
+       <T> T getInterfaceImplementation(ProvidedInterface aProvided, Class<T> aType );
+
+       /**
+        * Gets the runtime for a component.  
+        * @param aComponent Component for which we want to get the runtime.  
+        * @return Runtime.  
+        */
+       Object getRuntime(Component aComponent);
+       
+       /**
+        * Gets the runtime for a component based on the name of the component
+        * (excluding its context). 
+        * @param aName Component name. 
+        * @return Component name. 
+        */
+       Object getRuntime(String aName);
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java
new file mode 100644 (file)
index 0000000..a8a0ac1
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+/**
+ * Exception thrown when an error occurs in assembling the systems.
+ *
+ * @author Erik Brakkee
+ */
+public class SystemAssemblyException extends RuntimeException {
+
+       /**
+        * Constructs the exception. 
+        * @param aMsg Message. 
+        */
+       public SystemAssemblyException(String aMsg) { 
+               super(aMsg); 
+       }
+       
+       /**
+        * Constructs the exception. 
+        * @param aMsg Message
+        * @param aCause Cause. 
+        */
+       public SystemAssemblyException(String aMsg, Throwable aCause) { 
+               super(aMsg, aCause);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java
new file mode 100644 (file)
index 0000000..692c881
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class CompositeEdgeFilter implements EdgeFilter {
+    
+    private List<EdgeFilter> _filters; 
+    
+    public CompositeEdgeFilter() { 
+        _filters = new ArrayList<EdgeFilter>();
+    }
+    
+    public void add(EdgeFilter aFilter) { 
+        _filters.add(aFilter);
+    }
+
+    @Override
+    public boolean isViolated(Edge aEdge) {
+        for (EdgeFilter filter: _filters) { 
+            if ( filter.isViolated(aEdge) ) { 
+                return true; 
+            }
+        }
+        return false; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java
new file mode 100644 (file)
index 0000000..35d648f
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+/**
+ * Represents an application-independent edge of a graph. 
+ * Applications might choose to implement the Edge interface
+ * directly. 
+ * 
+ * @author Erik Brakkee
+ */
+public class DefaultEdge implements Edge {
+    
+    private Node _from; 
+    private Node _to; 
+    
+    public DefaultEdge(Node aFrom, Node aTo) { 
+        _from = aFrom;
+        _to = aTo; 
+    }
+
+    @Override
+    public Node getFrom() {
+        return _from;
+    }
+
+    @Override
+    public Node getTo() {
+        return _to; 
+    }
+    
+    @Override
+    public String toString() {
+        return "Edge(" + _from.getName() + ", " + _to.getName() + ")";
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java
new file mode 100644 (file)
index 0000000..925c08c
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+/**
+ * Default application-independent node. Specific applications of the graph might
+ * implement the Node interface directly.  
+ * @author Erik Brakkee
+ *
+ */
+public class DefaultNode implements Node {
+    
+    private String _name; 
+    
+    /**
+     * Constructs the node. 
+     * @param aName Node name. 
+     */
+    public DefaultNode(String aName) { 
+        _name = aName; 
+    }
+
+    /**
+     * Returns the node name. 
+     */
+    @Override
+    public String getName() {
+        return _name;
+    }
+
+    @Override
+    public boolean equals(Object aObj) {
+        if ( !(aObj instanceof Node)) { 
+            return false; 
+        }
+        Node node = (Node)aObj;
+        return _name.equals(node.getName());
+    }
+    
+    @Override
+    public int hashCode() {
+        return _name.hashCode();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Edge.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Edge.java
new file mode 100644 (file)
index 0000000..a340015
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+/**
+ * Represents an edge of a graph. 
+ * 
+ * @author Erik Brakkee
+ */
+public interface Edge {
+
+    /**
+     * @return The from part of the edge. 
+     */
+    Node getFrom();
+    
+    /**
+     * @return The to part of the edge. 
+     */
+    Node getTo();
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java
new file mode 100644 (file)
index 0000000..4ac39f6
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+import java.util.List;
+
+/**
+ * Edge factory used to extend a graph with new edges. 
+ * @author Erik Brakkee
+ *
+ * @param <NodeType> Type of node. 
+ */
+public interface EdgeFactory<NodeType extends Node> {
+    /**
+     * Computes a number of new edges to be added to the graph. 
+     * @param aFrom From node. 
+     * @param aTo To node. 
+     * @return List of edges from the from to the to node. 
+     */
+    List<Edge> create(NodeType aFrom, NodeType aTo); 
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java
new file mode 100644 (file)
index 0000000..b372f08
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+public interface EdgeFilter {
+
+    boolean isViolated(Edge aEdge); 
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java
new file mode 100644 (file)
index 0000000..c49f82c
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+public class EdgeSelector<FromType extends Node, ToType extends Node> {
+    
+    public static interface Selector<FromType extends Node, ToType extends Node> { 
+        void execute(FromType aFrom, ToType aTo);
+    }
+    
+    private Class<FromType> _fromType; 
+    private Class<ToType> _toType;
+    
+    public EdgeSelector(Class<FromType> aFrom, Class<ToType> aTo) {
+        _fromType = aFrom; 
+        _toType = aTo;
+    }
+
+    public void execute(Selector<FromType,ToType> aSelector, Edge aEdge) { 
+        if ( _fromType.isInstance(aEdge.getFrom()) && _toType.isInstance(aEdge.getTo())) { 
+            aSelector.execute((FromType)aEdge.getFrom(), (ToType)aEdge.getTo());
+        }    
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Graph.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Graph.java
new file mode 100644 (file)
index 0000000..0e4f6cc
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Represents a graph consisting of nodes and edges.
+ * 
+ * @author Erik Brakkee
+ */
+public class Graph {
+
+    private List<Node> _nodes;
+    private List<Edge> _edges;
+
+    /**
+     * Constructs the graph.
+     */
+    public Graph() {
+        _nodes = new ArrayList<Node>();
+        _edges = new ArrayList<Edge>();
+    }
+
+    /**
+     * Adds a node.
+     * 
+     * @param aNode
+     *            Node to add.
+     * @throws IllegalArgumentException
+     *             In case the node already exists. Node equality is checked
+     *             using <code>equals</code>.
+     */
+    public void addNode(Node aNode) {
+        if (_nodes.contains(aNode)) {
+            throw new IllegalArgumentException("Node '" + aNode.getName()
+                    + "' already exists");
+        }
+        _nodes.add(aNode);
+    }
+
+    /**
+     * Finds a node with the given name.
+     * 
+     * @param aName
+     *            Node name.
+     * @return Node or null if not found.
+     */
+    public Node findNode(String aName) {
+        for (Node node : _nodes) {
+            if (node.getName().equals(aName)) {
+                return node;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Removes a node.
+     * 
+     * @param aNode
+     *            Node to remove.
+     * @return True iff the node was removed.
+     * @throws IllegalArgumentException
+     *             In case there are edges of which the node is a part.
+     */
+    public boolean removeNode(Node aNode) {
+        if (!findOutgoing(aNode).isEmpty() || !findIncoming(aNode).isEmpty()) {
+            throw new IllegalArgumentException("Cannot remove node '"
+                    + aNode.getName()
+                    + "' because it is connected to one or more edges");
+        }
+        return _nodes.remove(aNode);
+    }
+
+    /**
+     * Adds a list of nodes.
+     * 
+     * @param aNodes
+     *            Nodes to add.
+     * 
+     * @see #addNode(Node)
+     */
+    public void addNodes(List<Node> aNodes) {
+        for (Node node : aNodes) {
+            addNode(node);
+        }
+    }
+
+    /**
+     * Adds an edge.
+     * 
+     * @param aEdge
+     *            Edge to add.
+     * @throws IllegalArgumentException
+     *             In case one of the nodes of the edges is not part of the
+     *             graph or if the same edge (as determined by
+     *             {@link #equals(Object)} is already a part of the graph.
+     */
+    public void addEdge(Edge aEdge) {
+        if (_edges.contains(aEdge)) {
+            throw new IllegalArgumentException("Edge '" + aEdge
+                    + "' already exists");
+        }
+        if (!_nodes.contains(aEdge.getFrom())) {
+            throw new IllegalArgumentException("From node '" + aEdge.getFrom()
+                    + "' from edge '" + aEdge + "' is not part of the graph");
+        }
+        if (!_nodes.contains(aEdge.getTo())) {
+            throw new IllegalArgumentException("To node '" + aEdge.getTo()
+                    + "' from edge '" + aEdge + "' is not part of the graph");
+        }
+        _edges.add(aEdge);
+    }
+
+    /**
+     * Removes an edge. 
+     * @param aEdge Edge to remove. 
+     * @return True if the edge was removed. 
+     */
+    public boolean removeEdge(Edge aEdge) {
+        return _edges.remove(aEdge);
+    }
+
+    /**
+     * Adds a number of edges. 
+     * @param aEdges Edges to add. 
+     */
+    public void addEdges(List<Edge> aEdges) {
+        for (Edge edge : aEdges) {
+            addEdge(edge);
+        }
+    }
+
+    /**
+     * Gets the nodes. 
+     * @return Copy of the list of nodes of the graph. 
+     */
+    public List<Node> getNodes() {
+        return new ArrayList<Node>(_nodes);
+    }
+
+    /**
+     * Gets the edges. 
+     * @return Copy of the list of edges of the graph. 
+     */
+    public List<Edge> getEdges() {
+        return new ArrayList<Edge>(_edges);
+    }
+
+    /**
+     * Extends the graph with edges using an edge factory. All combinations of 
+     * nodes are passed to the factory which creates additional edges. 
+     * @param aFactory Edge factory. 
+     */
+    public void extend(EdgeFactory aFactory) {
+        for (Node from : _nodes) {
+            for (Node to : _nodes) {
+                _edges.addAll(aFactory.create(from, to));
+            }
+        }
+    }
+    
+    /**
+     * Applies a filter to the graph for removing elements. 
+     * @param aFilter Filter to apply. 
+     */
+    public void applyFilter(EdgeFilter aFilter) {
+        for (Iterator<Edge> edge = _edges.iterator(); edge.hasNext(); ) { 
+            if (aFilter.isViolated(edge.next())) { 
+                edge.remove();
+            }
+        }
+    }
+
+    /**
+     * Finds all outgoing edges of a node. More specifically, finds 
+     * all edges <code>e</code> for which <code>e.getFrom().getName() = aNode.getName()</code>.
+     * @param aNode Node for which to find outgoing edges. 
+     * @return List of outgoing edges. 
+     */
+    public List<Edge> findOutgoing(Node aNode) {
+        List<Edge> result = new ArrayList<Edge>();
+        for (Edge edge : _edges) {
+            if (edge.getFrom().getName().equals(aNode.getName())) {
+                result.add(edge);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Finds all incoming edges of a node. 
+     * More specifically, finds 
+     * all edges <code>e</code> for which <code>e.getTo().getName() = aNode.getName()</code>.
+     * @param aNode Node for which to find incoming edges. 
+     * @return List of incoming edges. 
+     */
+    public List<Edge> findIncoming(Node aNode) {
+        List<Edge> result = new ArrayList<Edge>();
+        for (Edge edge : _edges) {
+            if (edge.getTo().getName().equals(aNode.getName())) {
+                result.add(edge);
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Implements a visitor design pattern.
+     * This loops over all nodes and all edges and invokes the appropriate visit
+     * methods on the visitor.  
+     * @param aVisitor Visitor. 
+     */
+    public void accept(Visitor aVisitor) {
+        List<Node> nodes = getNodes(); // copy to make sure the visitor can
+        // modify the
+        // list of nodes as part of the loop.
+        List<Edge> edges = getEdges(); // copy ..... (see above).
+
+        for (Node node : nodes) {
+            aVisitor.visitNode(node);
+        }
+        for (Edge edge : edges) {
+            aVisitor.visitEdge(edge);
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Node.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Node.java
new file mode 100644 (file)
index 0000000..d1df3c0
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+/**
+ * Represents a node in a graph. 
+ * @author Erik Brakkee
+ */
+public interface Node {
+    
+    /**
+     * Gets the node name uniquely identifying the node in the graph. 
+     * @return Node name. 
+     */
+    String getName();
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Visitor.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/Visitor.java
new file mode 100644 (file)
index 0000000..e65a535
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+/**
+ * Visitor of a graph. 
+ * @author Erik Brakkee.
+ *
+ */
+public interface Visitor {
+
+    /**
+     * Visits a node. Called by {@link Graph#accept(Visitor)}.
+     * @param aNode Node to visit. 
+     */
+    void visitNode(Node aNode); 
+    
+    /**
+     * Visits a node. Called by {@link Graph#accept(Visitor)}.
+     * @param aEdge Edge to visit. 
+     */
+    void visitEdge(Edge aEdge); 
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java
new file mode 100644 (file)
index 0000000..c921630
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.List;
+
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.Graph;
+import org.wamblee.system.graph.Node;
+import org.wamblee.system.graph.Visitor;
+
+/**
+ * Visitor that checks whether all externally provided interfaces are actually provided 
+ * by any of the internal components. 
+ * 
+ * @author Erik Brakkee
+ *
+ */
+public class CheckExternallyProvidedVisitor implements Visitor {
+    
+    private Graph _graph; 
+
+    /**
+     * Constructs the visitor. 
+     * @param aGraph Component graph. 
+     */
+    public CheckExternallyProvidedVisitor(Graph aGraph) { 
+        _graph = aGraph; 
+    }
+
+    @Override
+    public void visitEdge(Edge aEdge) {
+        // Empty.
+    }
+
+    @Override
+    public void visitNode(Node aNode) {
+        if ( aNode instanceof ExternalProvidedInterfaceNode) { 
+            ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode; 
+            List<Edge> edges = _graph.findOutgoing(provided);
+            if ( edges.size() > 2 ) { 
+                createDuplicateException("External provided interfaces has multiple internal matches", aNode, edges);
+            }
+            if ( edges.size() == 0 ) { 
+                throw new SystemAssemblyException(aNode + ": external provded interface is not provided by any of the internal components");
+            }
+        }
+    }
+    
+    private void createDuplicateException(String aMsg, Node aNode, List<Edge> edges) {
+        StringBuffer buf = new StringBuffer();
+        buf.append(aNode
+                + ": " + aMsg + ": ");
+        for (Edge edge : edges) {
+            buf.append(edge.getTo() + "/ ");
+        }
+        throw new SystemAssemblyException(buf.toString());
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java
new file mode 100644 (file)
index 0000000..1ce53d0
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.Graph;
+import org.wamblee.system.graph.Node;
+import org.wamblee.system.graph.Visitor;
+
+/**
+ * Visitor that checks whether all required external interfaces of the container
+ * are provided.
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class CheckExternallyRequiredVisitor implements Visitor {
+
+    private Log LOG = LogFactory.getLog(CheckExternallyRequiredVisitor.class);
+
+    private Graph _graph;
+
+    public CheckExternallyRequiredVisitor(Graph aGraph) {
+        _graph = aGraph;
+    }
+
+    @Override
+    public void visitEdge(Edge aEdge) {
+        // Empty.
+    }
+
+    @Override
+    public void visitNode(Node aNode) {
+        if (aNode instanceof ExternalRequiredInterfaceNode) {
+            ExternalRequiredInterfaceNode required = (ExternalRequiredInterfaceNode) aNode;
+            if (!required.getRequired().isOptional()
+                    && required.getRequired().getProvider() == null) {
+                throw new SystemAssemblyException(aNode
+                        + ": External required interface is not provided");
+            }
+
+            List<Edge> edges = _graph.findIncoming(aNode);
+
+            if (edges.isEmpty()) {
+                LOG.warn(aNode + ": Superfluous required interface");
+            }
+            for (Edge edge : edges) {
+                Node from = edge.getFrom();
+                assert from instanceof RequiredInterfaceNode;
+                RequiredInterfaceNode reqNode = (RequiredInterfaceNode)from;
+                if (!reqNode.getRequired().isOptional()
+                        && required.getRequired().isOptional()) {
+                    throw new SystemAssemblyException(
+                            aNode
+                                    + ": externally required interface is optional but a corresponding internal required interface is mandatory: "
+                                    + reqNode);
+                }
+            }
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java
new file mode 100644 (file)
index 0000000..608dfc1
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.List;
+
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.Graph;
+import org.wamblee.system.graph.Node;
+import org.wamblee.system.graph.Visitor;
+
+/**
+ * Visitor that checks whether required and provided interfaces are matched
+ * appropriately:
+ * <ul>
+ * <li>Each required interface is connected to at most one provided interface
+ * </li>
+ * <li>Required interfaces that are not optional must be connected to precisely
+ * one provided interface</li>
+ * </ul>
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class CheckRequiredProvidedMultiplicityVisitor implements Visitor {
+
+    private Graph _graph;
+
+    public CheckRequiredProvidedMultiplicityVisitor(Graph aGraph) {
+        _graph = aGraph;
+    }
+
+    @Override
+    public void visitEdge(Edge aEdge) {
+        // Empty
+    }
+
+    @Override
+    public void visitNode(Node aNode) {
+        if (aNode instanceof RequiredInterfaceNode) {
+            RequiredInterfaceNode required = (RequiredInterfaceNode) aNode;
+            List<Edge> edges = _graph.findOutgoing(aNode);
+            if (edges.size() > 1) {
+                createDuplicateException("Multiple providers of required interface found", aNode, edges);
+            }
+            if (edges.size() == 0 && !required.getRequired().isOptional()) {
+                throw new SystemAssemblyException(
+                        aNode
+                                + ": mandatpory required interface not provided by other components started earlier");
+            }
+        } else if ( aNode instanceof ExternalProvidedInterfaceNode) { 
+            List<Edge> edges = _graph.findOutgoing(aNode); 
+            if ( edges.size() > 1) { 
+                createDuplicateException("multiple internal matches for externally provided interface", aNode, edges);
+            }
+            if ( edges.size() == 0 ) { 
+                throw new SystemAssemblyException(aNode + ": external provided interface is not provided internally");
+            }
+        }
+    }
+
+    private void createDuplicateException(String aMsg, Node aNode, List<Edge> edges) {
+        StringBuffer buf = new StringBuffer();
+        buf.append(aNode
+                + ": " + aMsg + ": ");
+        for (Edge edge : edges) {
+            buf.append(edge.getTo() + "/ ");
+        }
+        throw new SystemAssemblyException(buf.toString());
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java
new file mode 100644 (file)
index 0000000..61f4e70
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.Graph;
+import org.wamblee.system.graph.Node;
+import org.wamblee.system.graph.Visitor;
+
+/**
+ * Checks whether the given component graph can be started in component
+ * order without any missing dependencies. 
+ * @author Erik Brakkee
+ *
+ */
+public class CheckStartupDependenciesVisitor implements Visitor {
+    
+    private Graph _graph; 
+    private List<Node> _available; 
+
+    /**
+     * Constructs the visitor. 
+     * @param aGraph Graph. 
+     */
+    public CheckStartupDependenciesVisitor(Graph aGraph) { 
+        _graph = aGraph; 
+        _available = new ArrayList<Node>();
+    }
+
+    @Override
+    public void visitEdge(Edge aEdge) {
+        // Empty
+    }
+
+    @Override
+    public void visitNode(Node aNode) {
+        List<Edge> edges = _graph.findOutgoing(aNode);
+        
+        // check dependencies.
+        for (Edge edge: edges) { 
+            Node dep = edge.getTo();
+            if ( !_available.contains(dep)) { 
+                throw new SystemAssemblyException(aNode + ": required dependency '" + dep + "' was not started");
+            }
+        }
+        
+        _available.add(aNode);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java
new file mode 100644 (file)
index 0000000..b41c41c
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.general.Pair;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.graph.CompositeEdgeFilter;
+import org.wamblee.system.graph.DefaultEdge;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.Graph;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Represents a component graph and provides the bridge from the 
+ * component model to a graph model. The graph model is easier
+ * to work with to implement specific actions and validations than 
+ * the component model. 
+ */
+public class ComponentGraph extends Graph {
+    
+    private boolean _isLinked; 
+    private CompositeEdgeFilter _edgeFilter; 
+
+    /**
+     * Constructs an empty component graph. 
+     */
+    public ComponentGraph() {
+        _isLinked = false; 
+        _edgeFilter = new CompositeEdgeFilter(); 
+    }
+    
+    /**
+     * Adds an externally required interface of a container.  
+     * This should be called before any components of the container are
+     * added. 
+     * @param aComponent Component requiring the interface. 
+     * @param aInterface Required interface. 
+     */
+    public void addRequiredInterface(Component aComponent, RequiredInterface aInterface) { 
+        addNode(new ExternalRequiredInterfaceNode(aComponent, aInterface));
+    }
+    
+    /**
+     * Adds an externally provided interface of a container.
+     * This should be called after all components of the container have been added.
+     * @param aComponent Component providing the interface.   
+     * @param aInterface Provided interface. 
+     */
+    public void addProvidedInterface(Component aComponent, ProvidedInterface aInterface) { 
+        addNode(new ExternalProvidedInterfaceNode(aComponent, aInterface));
+    }
+    
+    /**
+     * Validates the component graph. 
+     */
+    public void validate() { 
+        extend(new RequiredProvidedEdgeFactory());
+        applyFilter(_edgeFilter);
+        accept(new CheckRequiredProvidedMultiplicityVisitor(this));
+        accept(new CheckExternallyRequiredVisitor(this)); 
+        accept(new CheckExternallyProvidedVisitor(this));
+        accept(new CheckStartupDependenciesVisitor(this));
+    }
+    
+    /**
+     * Links provided and required interfaces together in the component
+     * model based on the graph model. 
+     */
+    public void link() {
+        if ( _isLinked ) { 
+            return; 
+        }
+        accept(new LinkVisitor());
+        _isLinked = true; 
+    }
+    
+    /**
+     * Finds a list of mappings of external provided interface to internal provided interface. 
+     * 
+     * @return List of pairs of external to internal interface. 
+     */
+    public List<Pair<ProvidedInterface, ProvidedInterface>> findExternalProvidedInterfaceMapping() { 
+        List<Pair<ProvidedInterface, ProvidedInterface>> result = 
+            new ArrayList<Pair<ProvidedInterface,ProvidedInterface>>(); 
+        for (Edge edge: getEdges()) { 
+            if ( edge.getFrom() instanceof ExternalProvidedInterfaceNode  && 
+                    edge.getTo() instanceof ProvidedInterfaceNode ) { 
+                result.add(new Pair<ProvidedInterface,ProvidedInterface>(
+                        ((ExternalProvidedInterfaceNode)edge.getFrom()).getProvided(), 
+                        ((ProvidedInterfaceNode)edge.getTo()).getProvided()
+                        )); 
+            }
+        }
+        return result; 
+    }
+    
+    /**
+     * Adds a component by adding required interfaces, components, and
+     * provided interfaces. 
+     * @param aComponent Component to add. 
+     */
+    public void addComponent(Component<?> aComponent) { 
+        // Add required interfaces. 
+        Node compNode = new ComponentNode(aComponent);
+        List<Node> requiredNodes = new ArrayList<Node>();
+        for (RequiredInterface required: aComponent.getRequiredInterfaces()) { 
+            Node reqNode = new RequiredInterfaceNode(aComponent, required); 
+            addNode(reqNode);
+            requiredNodes.add(reqNode);
+        }
+        // Add the component
+        addNode(compNode);
+     
+        // Edges from component to required interface. 
+        for (Node reqNode: requiredNodes) { 
+            addEdge(new DefaultEdge(compNode, reqNode));
+        }
+        
+        // Add provided interfaces
+        List<Node> providedNodes = new ArrayList<Node>();
+        for (ProvidedInterface provided: aComponent.getProvidedInterfaces()) { 
+            Node provNode = new ProvidedInterfaceNode(aComponent, provided); 
+            addNode(provNode);
+            providedNodes.add(provNode);
+        }
+        
+        // Edges from provided interface to component
+        for (Node provNode: providedNodes) { 
+            addEdge(new DefaultEdge(provNode, compNode));
+        }
+    }
+
+    public void addEdgeFilter(CompositeEdgeFilter aEdgeFilter) {
+        _edgeFilter.add(aEdgeFilter);    
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java
new file mode 100644 (file)
index 0000000..dc34426
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.core.Component;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Represents a component node. 
+ * @author Erik Brakkee. 
+ *
+ */
+public class ComponentNode implements Node {
+    
+    private Component<?> _component; 
+    
+    public ComponentNode(Component<?> aComponent) { 
+        _component = aComponent; 
+    }
+
+    @Override
+    public String getName() {
+        return _component.getQualifiedName();
+    }
+    
+    public Component<?> getComponent() {
+        return _component;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java
new file mode 100644 (file)
index 0000000..1007ae7
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFilter;
+
+/**
+ * Filter used to explicitly connect required and provided interfaces within a
+ * container.
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class ConnectExternalProvidedProvidedFilter implements EdgeFilter {
+
+    private String _externalProvided;
+    private String _component;
+    private String _provided;
+
+    public ConnectExternalProvidedProvidedFilter(String aExternalProvided, String aComponent,
+            String aProvided) {
+        _externalProvided = aExternalProvided; 
+        _component = aComponent; 
+        _provided = aProvided; 
+        if ( _externalProvided == null ) { 
+            throw new IllegalArgumentException("External provided interface name must be specified."); 
+        }
+        if ( _component == null ) { 
+            throw new IllegalArgumentException("Component name must be specified");
+        }
+        if ( _provided == null ) { 
+            throw new IllegalArgumentException("Provided interface name of internal component must be specified");
+        }
+    }
+
+    @Override
+    public boolean isViolated(Edge aEdge) {
+        if (aEdge.getFrom() instanceof ExternalProvidedInterfaceNode
+                && aEdge.getTo() instanceof ProvidedInterfaceNode) {
+            return isViolated((ExternalProvidedInterfaceNode) aEdge.getFrom(),
+                    (ProvidedInterfaceNode) aEdge.getTo());
+        }
+        return false;
+    }
+
+    private boolean isViolated(ExternalProvidedInterfaceNode aFrom,
+            ProvidedInterfaceNode aTo) {
+        if ( !aFrom.getName().equals(_externalProvided)) { 
+            return false; // wrong provided interface.
+        }
+        if ( aTo.getComponent().getName().equals(_component) && 
+               aTo.getProvided().getName().equals(_provided) ) { 
+            return false; // ok 
+        }
+        return true; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java
new file mode 100644 (file)
index 0000000..c708402
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFilter;
+
+/**
+ * Filter used to explicitly connect required and provided interfaces within a
+ * container.
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class ConnectRequiredExternallyRequiredEdgeFilter implements EdgeFilter {
+
+    private String _client;
+    private String _required;
+    private String _externalRequired;
+
+    public ConnectRequiredExternallyRequiredEdgeFilter(String aClient, String aRequired,
+            String aExternalRequired) {
+        _client = aClient;
+        _required = aRequired;
+        _externalRequired = aExternalRequired; 
+        if ( _client == null ) { 
+            throw new IllegalArgumentException("Client component must be specified"); 
+        }
+        if ( _required == null ) { 
+            throw new IllegalArgumentException("Required interface must be specified");
+        }
+        if ( _externalRequired == null ) { 
+            throw new IllegalArgumentException("External required interface must be specified");
+        }
+    }
+
+    @Override
+    public boolean isViolated(Edge aEdge) {
+        if (aEdge.getFrom() instanceof RequiredInterfaceNode
+                && aEdge.getTo() instanceof ExternalRequiredInterfaceNode) {
+            return isViolated((RequiredInterfaceNode) aEdge.getFrom(),
+                    (ExternalRequiredInterfaceNode) aEdge.getTo());
+        }
+        return false;
+    }
+
+    private boolean isViolated(RequiredInterfaceNode aFrom,
+            ExternalRequiredInterfaceNode aTo) {
+        if ( !aFrom.getComponent().getName().equals(_client)) { 
+            return false; // wrong component. 
+        }
+        if ( !(_required == null || aFrom.getRequired().getName().equals(_required))) { 
+            return false; // wrong interface
+        }
+        if ( !aTo.getRequired().getName().equals(_externalRequired)) { 
+            return true; // wrong externally required interface.  
+        }
+      
+        return false; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java
new file mode 100644 (file)
index 0000000..a1d2481
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFilter;
+
+/**
+ * Filter used to explicitly connect required and provided interfaces within a
+ * container.
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class ConnectRequiredProvidedEdgeFilter implements EdgeFilter {
+
+    private String _client;
+    private String _required;
+    private String _server;
+    private String _provided;
+
+    public ConnectRequiredProvidedEdgeFilter(String aClient, String aRequired,
+            String aServer, String aProvided) {
+        _client = aClient;
+        _required = aRequired;
+        _server = aServer;
+        _provided = aProvided;
+        if ( _client == null ) { 
+            throw new IllegalArgumentException("Client component must be specified"); 
+        }
+    }
+
+    @Override
+    public boolean isViolated(Edge aEdge) {
+        if (aEdge.getFrom() instanceof RequiredInterfaceNode
+                && aEdge.getTo() instanceof ProvidedInterfaceNode) {
+            return isViolated((RequiredInterfaceNode) aEdge.getFrom(),
+                    (ProvidedInterfaceNode) aEdge.getTo());
+        }
+        return false;
+    }
+
+    private boolean isViolated(RequiredInterfaceNode aFrom,
+            ProvidedInterfaceNode aTo) {
+        if (_client.equals(aFrom.getComponent().getName())
+                && (_required == null || _required.equals(aFrom.getRequired()
+                        .getName()))) {
+            // From part matches.
+            if ( _server == null ) { 
+                return true; // all connections are eliminated
+            }
+            if (_server.equals(aTo.getComponent().getName())
+                    && (_provided == null || _provided.equals(aTo.getProvided()
+                            .getName()))) {
+                // to part matches also
+                return false;
+            }
+            else { 
+                // From matches and to doesn't so edgefilter is violated.
+                return true; 
+            }
+        } else {
+            // From part does not match, restriction does not apply.
+            return false;
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java
new file mode 100644 (file)
index 0000000..c7fd7d0
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Represents an external provided interface of a container. 
+ * @author Erik Brakkee
+ *
+ */
+public class ExternalProvidedInterfaceNode implements Node {
+
+    private Component _component; 
+    private ProvidedInterface _provided; 
+    
+    public ExternalProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) {
+        _component = aComponent; 
+        _provided = aProvided; 
+    }
+    
+    @Override
+    public String getName() {
+        return _provided.getName(); 
+    }
+    
+    public Component getComponent() {
+        return _component;
+    }
+    
+    public ProvidedInterface getProvided() {
+        return _provided;
+    }
+    
+    @Override
+    public String toString() {
+        return _component.getQualifiedName() + ":" + _provided; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java
new file mode 100644 (file)
index 0000000..5c65ebd
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Represents an externally required interface of a container. 
+ * @author Erik Brakkee
+ *
+ */
+public class ExternalRequiredInterfaceNode implements Node {
+    
+    private Component _component;
+    private RequiredInterface _required; 
+
+    public ExternalRequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) {
+        _component = aComponent; 
+        _required = aRequired; 
+    }
+    
+    @Override
+    public String getName() {
+        return _required.getName(); 
+    }
+    
+    public Component getComponent() {
+        return _component;
+    }
+    
+    public RequiredInterface getRequired() {
+        return _required;
+    }
+    
+    @Override
+    public String toString() {
+        return _component.getQualifiedName() + ":" + _required;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java
new file mode 100644 (file)
index 0000000..cc2007f
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.system.graph.DefaultEdge;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.Node;
+import org.wamblee.system.graph.Visitor;
+
+/**
+ * Visitor that creates links between required and provided interfaces as
+ * described by the edges in the graph.
+ * 
+ * Specically it links together (1) required and provided interfaces of internal component 
+ * of a container and (2) the providers of externally required interfaces and internal required
+ * interfaces. 
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class LinkVisitor implements Visitor {
+
+    @Override
+    public void visitEdge(Edge aEdge) {
+        Node from = aEdge.getFrom();
+        Node to = aEdge.getTo();
+        if (from instanceof RequiredInterfaceNode) {
+            RequiredInterfaceNode required = (RequiredInterfaceNode) from;
+            if (to instanceof ProvidedInterfaceNode) {
+
+                ProvidedInterfaceNode provided = (ProvidedInterfaceNode) to;
+                required.getRequired().setProvider(provided.getProvided());
+
+            } else if (to instanceof ExternalRequiredInterfaceNode) {
+                ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) to;
+                ProvidedInterface provider = external.getRequired()
+                        .getProvider();
+                if (provider == null && !required.getRequired().isOptional()) {
+                    throw new SystemAssemblyException("Mandatory interface '"
+                            + from + "' is not provided.");
+                }
+                if ( provider != null ) { 
+                    required.getRequired().setProvider(provider);
+                }
+            }
+        } else if (from instanceof ProvidedInterfaceNode) {
+            // Provided interfaces can only be published after the system has
+            // started.
+        }
+    }
+
+    @Override
+    public void visitNode(Node aNode) {
+        // Empty.
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java
new file mode 100644 (file)
index 0000000..2fb2c0f
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Provided interface node. 
+ * @author Erik Brakkee
+ */
+public class ProvidedInterfaceNode implements Node {
+    
+    private Component _component; 
+    private ProvidedInterface _provided;
+    
+    public ProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) {
+        _component = aComponent; 
+        _provided = aProvided; 
+    }
+
+    @Override
+    public String getName() {
+        return _component.getQualifiedName() + ":" + _provided.getName(); 
+    }
+
+    public ProvidedInterface getProvided() {
+        return _provided;
+    }
+    
+    public Component getComponent() {
+        return _component;
+    }
+    
+    @Override
+    public String toString() {
+        return _component.getQualifiedName() + ":" + _provided; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java
new file mode 100644 (file)
index 0000000..b154051
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Required interface node. 
+ * @author Erik Brakkee
+ *
+ */
+public class RequiredInterfaceNode implements Node {
+    
+    private Component _component; 
+    private RequiredInterface _required; 
+    
+    public RequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) {
+        _component = aComponent; 
+        _required = aRequired; 
+    }
+
+    @Override
+    public String getName() {
+        return _component.getQualifiedName() + ":" + _required.getName();
+    }
+
+    public RequiredInterface getRequired() {
+        return _required;
+    }
+    
+    public Component getComponent() {
+        return _component;
+    }
+    
+    @Override
+    public String toString() {
+        return _component.getQualifiedName() + ":" + _required; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java
new file mode 100644 (file)
index 0000000..711501a
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.wamblee.system.graph.DefaultEdge;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFactory;
+import org.wamblee.system.graph.Node;
+
+/**
+ * Factory that creates edges between required and provided interfaces.
+ * Speciflcally it creates: 
+ * <ul>
+ *   <li> Edges between provided and required interfaces of a container. </li>
+ *   <li> Edges between required and externally required interfaces </li>
+ *   <li> Edges between externally provided and provided interfaces.  
+ * </ul>
+ * 
+ * @author Erik Brakkee
+ * 
+ */
+public class RequiredProvidedEdgeFactory implements EdgeFactory {
+
+    public RequiredProvidedEdgeFactory() {
+        // Empty.
+    }
+
+    @Override
+    public List<Edge> create(Node aFrom, Node aTo) {
+        List<Edge> result = new ArrayList<Edge>();
+        if (aFrom instanceof RequiredInterfaceNode) {
+            RequiredInterfaceNode required = (RequiredInterfaceNode) aFrom;
+            if (aTo instanceof ProvidedInterfaceNode) {
+             
+                ProvidedInterfaceNode provided = (ProvidedInterfaceNode) aTo;
+                if (required.getRequired()
+                        .implementedBy(provided.getProvided())) {
+                    result.add(new DefaultEdge(required, provided));
+                }
+            } else if (aTo instanceof ExternalRequiredInterfaceNode) {
+                ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) aTo;
+                if ( external.getRequired().covers(required.getRequired())) { 
+                    result.add(new DefaultEdge(required, external));
+                }
+            }
+        } else if ( aFrom instanceof ProvidedInterfaceNode) { 
+            ProvidedInterfaceNode provided = (ProvidedInterfaceNode)aFrom;
+            if ( aTo instanceof ExternalProvidedInterfaceNode) { 
+                ExternalProvidedInterfaceNode external = (ExternalProvidedInterfaceNode)aTo;
+                if (provided.getProvided().covers(external.getProvided())) { 
+                    result.add(new DefaultEdge(external, provided));
+                }
+            }
+        }
+        return result;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java
new file mode 100644 (file)
index 0000000..f886d78
--- /dev/null
@@ -0,0 +1,31 @@
+/**
+ * <h1>Graph component package </h1>
+ * 
+ * The graph component package provides the representation of a number of 
+ * components {@link Component} 
+ * their required and provided interfaces ({@link RequiredInterface} and 
+ * {@link ProvidedInterface}), and how these are connected together.
+ * 
+ * This package provides the bridge between the component model and the 
+ * representation of the components and their connections in a graph. 
+ * The component package provides various algorithms, filters, and 
+ * validations that are required for the implementation of a container. 
+ * 
+ * The main abstractions are: 
+ * <ul>
+ *   <li> {@link ComponentGraph}: A graph of components. This provides the logic
+ *   for creating a graph based on components. </li>
+ *   <li> {@link ComponentNode}: A node representing a component. </li>
+ *   <li> {@link RequiredInterfaceNode}: A node representing a required interface of a component. </li>
+ *   <li> {@link ProvidedInterfaceNode}: A node repesenting a provided interface of a component. </li>
+ *   <li> {@link ExternalRequiredInterfaceNode}: A node representing a required interface of a container </li>
+ *   <li> {@link ExternalProvidedInterfaceNode}: A node representing a provided interface of a container </li>  
+ * </ul> 
+ *
+ */
+package org.wamblee.system.graph.component;
+
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/package-info.java b/tags/wamblee-utils-0.2.1/system/general/src/main/java/org/wamblee/system/graph/package-info.java
new file mode 100644 (file)
index 0000000..6a2318e
--- /dev/null
@@ -0,0 +1,20 @@
+/**
+ * <h1>Graph package</h1>
+ * 
+ * The graph package provides a general very simple abstraction of a graph. 
+ * It was developed for the IOC container to represent dependences between 
+ * components through their required and provided interfaces.
+ * 
+ * The graph package supports a number of simple graph traversal operations, graph
+ * extension operations, and a visitor pattern. 
+ * 
+ * The main abstractions are: 
+ * <ul>
+ *    <li> {@link Graph}: The graph itself. </li> 
+ *    <li> {@link Node}: A node of a graph. </li>
+ *    <li> {@link Edge}: An edge of a graph> </li>
+ *    <li> {@link Visitor}: A visitor for implementing various operations on a graph. </li>
+ *    <li> {@link EdgeFactory}: For extending the graph with new edges </li>
+ * </ul>
+ */
+package org.wamblee.system.graph;
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java
new file mode 100644 (file)
index 0000000..cf67b24
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.DefaultScope;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.test.EventTracker;
+
+import junit.framework.TestCase;
+
+public class AdapterTestCase extends TestCase {
+       
+       protected Scope _scope;
+       static EventTracker<String> EVENT_TRACKER;
+
+       @Override
+       protected void setUp() throws Exception {
+               super.setUp();
+               EVENT_TRACKER = new EventTracker<String>();
+               _scope = new DefaultScope(new ProvidedInterface[0]);
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java
new file mode 100644 (file)
index 0000000..5e4f868
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.container.Container;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.test.AssertionUtils;
+
+public class ClassAdapterTest extends AdapterTestCase {
+
+
+       public void testSimpleConstructorInjection() { 
+               ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+               x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+               x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
+        ClassConfiguration x4Config = new ClassConfiguration(X4.class);
+        x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+        
+        ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
+        ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
+        
+        Container container = new Container("top", new Component[] { 
+                       x1Adapter, x4Adapter
+           }, new ProvidedInterface[0], new RequiredInterface[0]);
+        
+        Scope scope = container.start();
+        AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" },
+                       EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+        
+        Object obj1 = scope.getRuntime(x1Adapter);
+        assertTrue(obj1 instanceof X1); 
+        Object obj4 = scope.getRuntime(x4Adapter);
+        assertTrue(obj4 instanceof X4);
+        
+        X1 x1 = (X1) obj1;
+        X4 x4 = (X4) obj4;
+       
+        assertSame(x1, x4.getX1());
+       }
+       
+       public void testConstructorAndSetterInjection() {
+           ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+           x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+        x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
+        ClassConfiguration x4Config = new ClassConfiguration(X4.class);
+        x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+        ClassConfiguration x8Config = new ClassConfiguration(X8.class);
+        x8Config.getObjectConfig().getSetterConfig().initAllSetters();
+        
+        ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
+        ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
+        ClassAdapter x8Adapter = new ClassAdapter("x8", x8Config);
+        
+        Container container = new Container("top", new Component[] { 
+                x1Adapter, x4Adapter, x8Adapter
+        }, new ProvidedInterface[0], new RequiredInterface[0]);
+        
+        Scope scope = container.start();
+        AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", "x8(x1)", "x8.setX4(x4)" },
+                EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+        
+        Object obj1 = scope.getRuntime(x1Adapter);
+        assertTrue(obj1 instanceof X1); 
+        Object obj4 = scope.getRuntime(x4Adapter);
+        assertTrue(obj4 instanceof X4);
+        Object obj8 = scope.getRuntime(x8Adapter); 
+        
+        X1 x1 = (X1) obj1;
+        X4 x4 = (X4) obj4;
+        X8 x8 = (X8) obj8; 
+        
+        assertSame(x4, x8.getX4());
+        assertSame(x1, x8.getX1());
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java
new file mode 100644 (file)
index 0000000..8d5703d
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.RequiredInterfaceComparator;
+import org.wamblee.test.AssertionUtils;
+
+public class ClassConfigurationTest extends AdapterTestCase {
+
+    public void testConstructorConfig() {
+        ClassConfiguration classConfig = new ClassConfiguration(X1.class);
+
+        ConstructorConfiguration config = classConfig.getConstructorConfig()
+                .greedy();
+        
+        ProvidedInterface provided = new DefaultProvidedInterface("arg",
+                String.class);
+        List<RequiredInterface> required = classConfig.getRequiredInterfaces();
+
+        assertEquals(1, required.size());
+        assertFalse(required.get(0).isOptional());
+
+        required.get(0).setProvider(provided);
+
+        _scope.publishInterface(provided, "hello");
+        classConfig.create(_scope);
+
+        AssertionUtils.assertEquals(new String[] { "x1(hello)" },
+                AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread())
+                        .toArray());
+    }
+
+    public void testConstructorConfigWithSetters() {
+        ClassConfiguration classConfig = new ClassConfiguration(X7.class);
+
+        classConfig.getConstructorConfig().select(Boolean.class);
+        classConfig.getObjectConfig().getSetterConfig().initAllSetters().values("setPort").setValue(0, 10);
+        
+        ProvidedInterface providedBoolean = new DefaultProvidedInterface("boolean",
+                Boolean.class);
+        ProvidedInterface providedHost = new DefaultProvidedInterface("host", String.class);
+        List<RequiredInterface> required = classConfig.getRequiredInterfaces();
+
+        Collections.sort(required, new RequiredInterfaceComparator());
+        assertEquals(2, required.size());
+        assertEquals("arg0", required.get(0).getName());
+
+        required.get(0).setProvider(providedBoolean);
+        required.get(1).setProvider(providedHost);
+
+        _scope.publishInterface(providedBoolean, true);
+        _scope.publishInterface(providedHost, "host.name.org");
+        
+        Object obj = classConfig.create(_scope);
+        assertTrue(obj instanceof X7);
+        X7 x7 = (X7)obj;
+        assertNotNull(x7.getBoolean());
+        assertTrue(x7.getBoolean());
+        assertNull(x7.getHost());
+        assertNull(x7.getPort());
+
+        classConfig.inject(_scope, obj);
+        
+        assertEquals("host.name.org", x7.getHost());
+        assertEquals(10, x7.getPort().intValue());
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java
new file mode 100644 (file)
index 0000000..0cec6fb
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.util.List;
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.test.AssertionUtils;
+
+public class ConstructorConfigurationTest extends AdapterTestCase {
+
+       public void testGreedyUnique() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+                               .greedy();
+               ProvidedInterface provided = new DefaultProvidedInterface("arg",
+                               String.class);
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+
+               assertEquals(1, required.size());
+               assertFalse(required.get(0).isOptional());
+
+               required.get(0).setProvider(provided);
+
+               _scope.publishInterface(provided, "hello");
+               config.create(_scope);
+
+               AssertionUtils.assertEquals(new String[] { "x1(hello)" }, AdapterTestCase.EVENT_TRACKER
+                               .getEvents(Thread.currentThread()).toArray());
+       }
+
+       public void testGreedyNonUnique() {
+               try {
+                       ConstructorConfiguration config = new ConstructorConfiguration(
+                                       X2.class).greedy();
+               } catch (SystemAssemblyException e) {
+                       // e.printStackTrace();
+                       return;
+               }
+               fail();
+       }
+
+       public void testSpecificConstructor() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X2.class)
+                               .select(String.class);
+               ProvidedInterface provided = new DefaultProvidedInterface("arg",
+                               String.class);
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+
+               assertEquals(1, required.size());
+               required.get(0).setProvider(provided);
+
+               _scope.publishInterface(provided, "hello");
+               config.create(_scope);
+
+               AssertionUtils.assertEquals(new String[] { "x2(hello)" }, AdapterTestCase.EVENT_TRACKER
+                               .getEvents(Thread.currentThread()).toArray());
+       }
+
+       public void testSetValue() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+                               .greedy();
+               config.getParameters().setValue(0, "bla");
+
+               config.create(_scope);
+
+               AssertionUtils.assertEquals(new String[] { "x1(bla)" }, AdapterTestCase.EVENT_TRACKER
+                               .getEvents(Thread.currentThread()).toArray());
+       }
+
+       public void testOptionalValueProvided() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+                               .greedy();
+               config.getParameters().setOptional(0);
+               ProvidedInterface provided = new DefaultProvidedInterface("arg",
+                               String.class);
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+
+               assertEquals(1, required.size());
+               required.get(0).setProvider(provided);
+
+               _scope.publishInterface(provided, "hello");
+               config.create(_scope);
+
+               AssertionUtils.assertEquals(new String[] { "x1(hello)" }, AdapterTestCase.EVENT_TRACKER
+                               .getEvents(Thread.currentThread()).toArray());
+       }
+
+       public void testOptionalValueMissing() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X1.class)
+                               .greedy();
+               config.getParameters().setOptional(0);
+               assertTrue(config.getRequiredInterfaces().get(0).isOptional());
+
+               config.create(_scope);
+
+               AssertionUtils.assertEquals(new String[] { "x1(null)" }, AdapterTestCase.EVENT_TRACKER
+                               .getEvents(Thread.currentThread()).toArray());
+       }
+
+       public void testIgnoredNonPublic() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
+                               .greedy();
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               assertEquals(0, config.getParameters().getTypes().length);
+       }
+
+       public void testNonPublicConstructor() {
+               ConstructorConfiguration config = new ConstructorConfiguration(X3.class)
+                               .setNonPublic(true).greedy();
+               ProvidedInterface provided = new DefaultProvidedInterface("arg",
+                               String.class);
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+
+               assertEquals(1, required.size());
+               assertFalse(required.get(0).isOptional());
+
+               required.get(0).setProvider(provided);
+
+               _scope.publishInterface(provided, "hello");
+               config.create(_scope);
+
+               AssertionUtils.assertEquals(new String[] { "x3(hello)" }, AdapterTestCase.EVENT_TRACKER
+                               .getEvents(Thread.currentThread()).toArray());
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java
new file mode 100644 (file)
index 0000000..938a122
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import org.wamblee.system.core.Scope;
+import org.wamblee.test.AssertionUtils;
+
+public class DefaultContainerTest extends AdapterTestCase {
+
+    public void testConstructorInjection() {
+        ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+        x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
+        x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+        
+        ClassConfiguration x4Config = new ClassConfiguration(X4.class);
+        x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+
+        DefaultContainer container = new DefaultContainer("top").addComponent(
+                "x1", x1Config).addComponent("x4", x4Config);
+
+        Scope scope = container.start();
+        AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" },
+                EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+
+        Object obj = scope.getRuntime("x1");
+        assertTrue(obj instanceof X1);
+        obj = scope.getRuntime("x4");
+        assertTrue(obj instanceof X4);
+    }
+    
+    public void testConstructorInjectionAndSetterInjection() {
+        ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+        x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
+        x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+        
+        X8 x8 = new X8(null); 
+        EVENT_TRACKER.clear();
+
+        ClassConfiguration x4Config = new ClassConfiguration(X4.class);
+        x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+        
+        ObjectConfiguration x8Config = new ObjectConfiguration(X8.class);
+        x8Config.getSetterConfig().initAllSetters();
+        
+        DefaultContainer container = new DefaultContainer("top").addComponent(
+                "x1", x1Config).addComponent("x4", x4Config).addComponent("x8", x8, x8Config);
+
+        Scope scope = container.start();
+        AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)",
+                "x8.setX4(x4)"},
+                EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+
+        Object obj1 = scope.getRuntime("x1");
+        assertTrue(obj1 instanceof X1);
+        Object obj4 = scope.getRuntime("x4");
+        assertTrue(obj4 instanceof X4);
+        Object obj8 = scope.getRuntime("x8");
+        assertSame(x8, obj8);
+        assertSame(obj4, x8.getX4());
+    }
+    
+    public void testWrongObjectType() { 
+        final DefaultContainer container = new DefaultContainer("top");
+        AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+            @Override
+            public void run() throws Exception {
+                container.addComponent("x", "y", new ObjectConfiguration(Integer.class));   
+            }
+        }, IllegalArgumentException.class);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java
new file mode 100644 (file)
index 0000000..0c6825e
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.wamblee.system.container.Container;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.RequiredInterfaceComparator;
+import org.wamblee.system.core.Scope;
+import org.wamblee.test.AssertionUtils;
+
+public class ObjectAdapterTest extends AdapterTestCase {
+
+       public void testSetterInjection() {
+           
+           ClassConfiguration x1Config = new ClassConfiguration(X1.class);
+           x1Config.getObjectConfig().getSetterConfig().initAllSetters();
+           x1Config.getConstructorConfig().getParameters().setValue(0, "hello");
+              
+        ClassConfiguration x4Config = new ClassConfiguration(X4.class);
+        x4Config.getObjectConfig().getSetterConfig().initAllSetters();
+        ObjectConfiguration x8Config = new ObjectConfiguration(X8.class);
+        x8Config.getSetterConfig().initAllSetters();
+        
+        X1 x1 = new X1(); 
+        X8 x8 = new X8(x1);
+        
+        ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config);
+        ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config);
+        ObjectAdapter x8Adapter = new ObjectAdapter("x8", x8, x8Config);
+        
+        Container container = new Container("top", new Component[] { 
+                x1Adapter, x4Adapter, x8Adapter
+        }, new ProvidedInterface[0], new RequiredInterface[0]);
+        
+        EVENT_TRACKER.clear();
+        Scope scope = container.start();
+        AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", "x8.setX4(x4)" },
+                EVENT_TRACKER.getEvents(Thread.currentThread()).toArray());
+        
+        Object obj1 = scope.getRuntime(x1Adapter);
+        assertTrue(obj1 instanceof X1); 
+        Object obj4 = scope.getRuntime(x4Adapter);
+        assertTrue(obj4 instanceof X4);
+        Object obj8 = scope.getRuntime(x8Adapter);
+        assertSame(x8, obj8);
+        
+        X4 x4 = (X4) obj4;
+       
+        
+        assertSame(x4, x8.getX4());
+        assertSame(x1, x8.getX1());
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java
new file mode 100644 (file)
index 0000000..aebdc3d
--- /dev/null
@@ -0,0 +1,364 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import javax.sql.DataSource;
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.RequiredInterfaceComparator;
+import org.wamblee.test.AssertionUtils;
+
+public class SetterConfigurationTest extends AdapterTestCase {
+
+       public void testOneSetter() {
+               SetterConfiguration config = new SetterConfiguration(X5.class);
+               config.initAllSetters();
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               assertEquals(1, required.size());
+               assertEquals("setValue.0", required.get(0).getName());
+
+               ProvidedInterface provided = new DefaultProvidedInterface("janse",
+                               String.class);
+               required.get(0).setProvider(provided);
+               _scope.publishInterface(provided, "hello");
+
+               X5 obj = new X5();
+               assertNull(obj.getValue());
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getValue());
+       }
+
+       public void testPrivateSetter() {
+               SetterConfiguration config = new SetterConfiguration(X5.class);
+               config.setNonPublic(true);
+               config.initAllSetters();
+               List<RequiredInterface> required = new ArrayList<RequiredInterface>(
+                               config.getRequiredInterfaces());
+               Collections.sort(required, new Comparator<RequiredInterface>() {
+                       @Override
+                       public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+                               return aO1.getName().compareTo(aO2.getName());
+                       }
+               });
+               assertEquals(2, required.size());
+               assertEquals("setValue.0", required.get(0).getName());
+               assertEquals("setXyz.0", required.get(1).getName());
+
+               ProvidedInterface providedString = new DefaultProvidedInterface(
+                               "janse", String.class);
+               assertTrue(required.get(0).implementedBy(providedString));
+               required.get(0).setProvider(providedString);
+               _scope.publishInterface(providedString, "hello");
+
+               ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
+                               Integer.class);
+               assertTrue(required.get(1).implementedBy(providedInt));
+               required.get(1).setProvider(providedInt);
+               _scope.publishInterface(providedInt, 100);
+
+               X5 obj = new X5();
+               assertNull(obj.getValue());
+               assertNull(obj.getXyz());
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getValue());
+               assertEquals(100, obj.getXyz().intValue());
+       }
+
+       public void testInheritance() {
+               SetterConfiguration config = new SetterConfiguration(X9.class);
+               config.setNonPublic(true);
+               config.initAllSetters();
+               List<RequiredInterface> required = new ArrayList<RequiredInterface>(
+                               config.getRequiredInterfaces());
+               Collections.sort(required, new Comparator<RequiredInterface>() {
+                       @Override
+                       public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+                               return aO1.getName().compareTo(aO2.getName());
+                       }
+               });
+               assertEquals(3, required.size());
+               assertEquals("setFlag.0", required.get(0).getName());
+               assertEquals("setValue.0", required.get(1).getName());
+               assertEquals("setXyz.0", required.get(2).getName());
+
+               ProvidedInterface providedBoolean = new DefaultProvidedInterface(
+                               "janse", Boolean.class);
+               assertTrue(required.get(0).implementedBy(providedBoolean));
+               required.get(0).setProvider(providedBoolean);
+               _scope.publishInterface(providedBoolean, true);
+
+               ProvidedInterface providedString = new DefaultProvidedInterface(
+                               "janse", String.class);
+               assertTrue(required.get(1).implementedBy(providedString));
+               required.get(1).setProvider(providedString);
+               _scope.publishInterface(providedString, "hello");
+
+               ProvidedInterface providedInt = new DefaultProvidedInterface("xxx",
+                               Integer.class);
+               assertTrue(required.get(2).implementedBy(providedInt));
+               required.get(2).setProvider(providedInt);
+               _scope.publishInterface(providedInt, 100);
+
+               X9 obj = new X9();
+               assertNull(obj.getValue());
+               assertNull(obj.getXyz());
+               assertFalse(obj.isFlag());
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getValue());
+               assertEquals(100, obj.getXyz().intValue());
+               assertTrue(obj.isFlag());
+       }
+
+       public void testMultipleSetters() {
+               SetterConfiguration config = new SetterConfiguration(X6.class).initAllSetters();
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               Collections.sort(required, new RequiredInterfaceComparator());
+               assertEquals(2, required.size());
+               assertEquals("setHost.0", required.get(0).getName());
+               assertEquals("setPort.0", required.get(1).getName());
+
+               ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+                               String.class);
+               required.get(0).setProvider(provided0);
+               _scope.publishInterface(provided0, "hello");
+
+               ProvidedInterface provided1 = new DefaultProvidedInterface("port",
+                               Integer.class);
+               required.get(1).setProvider(provided1);
+               _scope.publishInterface(provided1, 10);
+
+               X6 obj = new X6();
+               assertNull(obj.getHost());
+               assertNull(obj.getPort());
+
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getHost());
+               assertEquals(10, obj.getPort().intValue());
+       }
+
+       public void testInvokeWrongType() {
+               final SetterConfiguration config = new SetterConfiguration(X5.class).initAllSetters();
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               assertEquals(1, required.size());
+               assertEquals("setValue.0", required.get(0).getName());
+
+               ProvidedInterface provided = new DefaultProvidedInterface("janse",
+                               String.class);
+               required.get(0).setProvider(provided);
+               _scope.publishInterface(provided, "hello");
+
+               final X6 obj = new X6();
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               config.inject(_scope, obj);
+                       }
+               }, IllegalArgumentException.class);
+       }
+
+       public void testSetExplicitValue() {
+               SetterConfiguration config = new SetterConfiguration(X5.class).initAllSetters();
+               config.values("setValue").setValue(0, "bladibla");
+
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               assertEquals(0, required.size());
+
+               X5 obj = new X5();
+               assertNull(obj.getValue());
+               config.inject(_scope, obj);
+               assertEquals("bladibla", obj.getValue());
+       }
+
+       public void testClear() {
+               SetterConfiguration config = new SetterConfiguration(X6.class);
+               config.clear();
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               Collections.sort(required, new RequiredInterfaceComparator());
+               assertEquals(0, required.size());
+
+               X6 obj = new X6();
+               assertNull(obj.getHost());
+               assertNull(obj.getPort());
+
+               config.inject(_scope, obj);
+
+               assertNull(obj.getHost());
+               assertNull(obj.getPort());
+       }
+
+       public void testAddByName() {
+               SetterConfiguration config = new SetterConfiguration(X6.class);
+               config.clear().add("setHost");
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               Collections.sort(required, new RequiredInterfaceComparator());
+               assertEquals(1, required.size());
+               assertEquals("setHost.0", required.get(0).getName());
+
+               ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+                               String.class);
+               required.get(0).setProvider(provided0);
+               _scope.publishInterface(provided0, "hello");
+
+               X6 obj = new X6();
+               assertNull(obj.getHost());
+               assertNull(obj.getPort());
+
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getHost());
+               assertNull(obj.getPort());
+       }
+       
+       public void testAddByType() { 
+               SetterConfiguration config = new SetterConfiguration(X6.class);
+               config.clear().addSetter(String.class);
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               Collections.sort(required, new RequiredInterfaceComparator());
+               assertEquals(1, required.size());
+               assertEquals("setHost.0", required.get(0).getName());
+
+               ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+                               String.class);
+               required.get(0).setProvider(provided0);
+               _scope.publishInterface(provided0, "hello");
+
+               X6 obj = new X6();
+               assertNull(obj.getHost());
+               assertNull(obj.getPort());
+
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getHost());
+               assertNull(obj.getPort());
+       }
+       
+       public void testAddPrivate() { 
+               X5 obj = new X5();
+               final SetterConfiguration config = new SetterConfiguration(X5.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { 
+                       @Override
+                       public void run() throws Exception {
+                               config.add("xyz");      
+                       }
+               }, IllegalArgumentException.class);
+               
+               config.setNonPublic(true);
+               config.clear();
+               config.add("setXyz");
+               assertEquals(1, config.getRequiredInterfaces().size());
+       }
+
+       public void testAddNonExisting() {
+               final SetterConfiguration config = new SetterConfiguration(X6.class);
+               config.clear();
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               config.add("bladibla");
+                       }
+               }, IllegalArgumentException.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               config.addSetter(DataSource.class);
+                       }
+               }, IllegalArgumentException.class);
+       }
+       
+       public void testAddByTypeNonUnique() { 
+               final SetterConfiguration config = new SetterConfiguration(X11.class);
+               config.clear();
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               config.addSetter(String.class);
+                       }
+               }, IllegalArgumentException.class);
+       }
+
+       public void testRemove() {
+               SetterConfiguration config = new SetterConfiguration(X6.class).initAllSetters();
+               config.remove("setPort");
+               List<RequiredInterface> required = config.getRequiredInterfaces();
+               Collections.sort(required, new RequiredInterfaceComparator());
+               assertEquals(1, required.size());
+               assertEquals("setHost.0", required.get(0).getName());
+
+               ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+                               String.class);
+               required.get(0).setProvider(provided0);
+               _scope.publishInterface(provided0, "hello");
+
+               X6 obj = new X6();
+               assertNull(obj.getHost());
+               assertNull(obj.getPort());
+
+               config.inject(_scope, obj);
+               assertEquals("hello", obj.getHost());
+               assertNull(obj.getPort());
+       }
+       
+       public void testRemoveByMethodObject() throws NoSuchMethodException {
+        SetterConfiguration config = new SetterConfiguration(X6.class).initAllSetters();
+        config.remove(X6.class.getMethod("setPort", Integer.class));
+        List<RequiredInterface> required = config.getRequiredInterfaces();
+        Collections.sort(required, new RequiredInterfaceComparator());
+        assertEquals(1, required.size());
+        assertEquals("setHost.0", required.get(0).getName());
+
+        ProvidedInterface provided0 = new DefaultProvidedInterface("janse",
+                String.class);
+        required.get(0).setProvider(provided0);
+        _scope.publishInterface(provided0, "hello");
+
+        X6 obj = new X6();
+        assertNull(obj.getHost());
+        assertNull(obj.getPort());
+
+        config.inject(_scope, obj);
+        assertEquals("hello", obj.getHost());
+        assertNull(obj.getPort());
+    }
+
+       public void testRemoveNonExisting() {
+               final SetterConfiguration config = new SetterConfiguration(X6.class);
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               config.remove("bladibla");
+                       }
+               }, IllegalArgumentException.class);
+       }
+       
+       public void testOverridingSetters() { 
+               SetterConfiguration config = new SetterConfiguration(X10.class).initAllSetters();
+               assertEquals(2, config.getRequiredInterfaces().size());
+               List<Method> methods = config.getSetters(); 
+               assertEquals(2, methods.size());
+               for (Method method: methods) { 
+                       assertEquals(X10.class, method.getDeclaringClass());
+               }
+               
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X1.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X1.java
new file mode 100644 (file)
index 0000000..b17a27c
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X1 {
+       public X1() {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x1()");
+       }
+
+       public X1(String aValue) {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")");
+       }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X10.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X10.java
new file mode 100644 (file)
index 0000000..fc8b90a
--- /dev/null
@@ -0,0 +1,26 @@
+package org.wamblee.system.adapters;
+
+public class X10 extends X6 {
+
+       
+       @Override
+       public void setHost(String aHost) {
+               super.setHost(aHost);
+       }
+       
+       @Override
+       public String getHost() {
+               return super.getHost();
+       }
+       
+       @Override
+       public Integer getPort() {
+               return super.getPort();
+       }
+       
+       @Override
+       public void setPort(Integer aPort) {
+               super.setPort(aPort);
+       }
+       
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X11.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X11.java
new file mode 100644 (file)
index 0000000..4ddc11e
--- /dev/null
@@ -0,0 +1,14 @@
+package org.wamblee.system.adapters;
+
+public class X11 {
+       
+       
+       public void setX(String aValue) { 
+               
+       }
+       
+       public void setY(String aValue) { 
+               
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X2.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X2.java
new file mode 100644 (file)
index 0000000..50a5902
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X2 {
+       public X2(Integer aInteger) {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aInteger + ")");
+       }
+
+       public X2(String aValue) {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aValue + ")");
+       }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X3.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X3.java
new file mode 100644 (file)
index 0000000..4601a03
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X3 {
+       public X3() {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x3()");
+       }
+
+       protected X3(String aValue) {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")");
+       }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X4.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X4.java
new file mode 100644 (file)
index 0000000..8d086a8
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X4 {
+
+       private X1 _x1; 
+       
+       public X4(X1 aX1) {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)");
+               _x1 = aX1;
+       }
+       
+       public X1 getX1() {
+               return _x1;
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X5.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X5.java
new file mode 100644 (file)
index 0000000..c0a8244
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X5 {
+    
+    private String _value; 
+    private Integer _xyz; 
+    
+       public X5() {
+       
+       }
+
+       public void setValue(String aValue) { 
+           AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue + ")");
+           _value = aValue; 
+       }
+       
+       public String getValue() {
+        return _value;
+    }
+       
+       public void doSomething() { 
+           // Empty.
+       }
+       
+       private void setXyz(int aXyz) { 
+               _xyz = aXyz;
+       }
+       
+       public Integer getXyz() {
+               return _xyz;
+       }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X6.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X6.java
new file mode 100644 (file)
index 0000000..06b7b5f
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X6 {
+    
+    private String _host; 
+    private Integer _port; 
+    
+       public X6() {
+       
+       }
+
+       public Integer getPort() {
+        return _port;
+    }
+       
+       public void setPort(Integer aPort) {
+        _port = aPort;
+    }
+       
+       public String getHost() {
+        return _host;
+    }
+       
+       public void setHost(String aHost) {
+        _host = aHost;
+    }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X7.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X7.java
new file mode 100644 (file)
index 0000000..5052018
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X7 {
+    
+    private String _host; 
+    private Integer _port;
+    private Boolean _boolean; 
+    
+       public X7(Boolean aBoolean) {
+          _boolean = aBoolean; 
+       }
+       
+       public Boolean getBoolean() {
+        return _boolean;
+    }
+
+       public Integer getPort() {
+        return _port;
+    }
+       
+       public void setPort(Integer aPort) {
+        _port = aPort;
+    }
+       
+       public String getHost() {
+        return _host;
+    }
+       
+       public void setHost(String aHost) {
+        _host = aHost;
+    }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X8.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X8.java
new file mode 100644 (file)
index 0000000..84b450f
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright 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.wamblee.system.adapters;
+
+public class X8 {
+
+       private X1 _x1;
+       private X4 _x4; 
+       
+       public X8(X1 aX1) {
+               AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)");
+               _x1 = aX1;
+       }
+       
+       public void setX4(X4 aX4) {
+           AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)");
+        _x4 = aX4;
+    }
+       
+       public X4 getX4() {
+        return _x4;
+    }
+       
+       public X1 getX1() {
+               return _x1;
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X9.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/adapters/X9.java
new file mode 100644 (file)
index 0000000..6b30541
--- /dev/null
@@ -0,0 +1,18 @@
+package org.wamblee.system.adapters;
+
+public class X9 extends X5 {
+       
+       private boolean _flag; 
+       
+       public X9() { 
+               
+       }
+
+       public boolean isFlag() {
+               return _flag;
+       }
+       
+    public void setFlag(boolean aFlag) {
+               _flag = aFlag;
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java
new file mode 100644 (file)
index 0000000..afcc581
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright 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.wamblee.system.components;
+
+import java.util.Properties;
+
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DerbyDatabase;
+import org.wamblee.system.components.ORMappingConfig.DatabaseType;
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.Scope;
+
+public class DatabaseComponent extends AbstractComponent<Database> {
+    
+    private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps", Properties.class);
+    
+    private Database _database; 
+    
+    public DatabaseComponent(String aName, Database aDatabase) { 
+        super(aName); 
+        _database = aDatabase;
+        addProvidedInterface(DB_PROPS);
+    }
+
+    @Override
+    protected Database doStart(Scope aScope) {
+        _database.start(); 
+        
+        Properties props = new Properties();
+        if ( _database instanceof DerbyDatabase ) { 
+            props.put("database.type", DatabaseType.DERBY.toString());
+        } else { 
+            throw new IllegalArgumentException("Unknown database type " + _database); 
+        }
+        //props.put("database.driver", _database.getDriverClassName());
+        props.put("database.url", _database.getJdbcUrl());
+        props.put("database.username", _database.getUsername());
+        props.put("database.password", _database.getPassword());
+
+        addInterface(DB_PROPS, props, aScope);
+        return _database; 
+    }
+
+    @Override
+    protected void doStop(Database aRuntime) {
+        _database.stop();
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java
new file mode 100644 (file)
index 0000000..4c100fc
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright 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.wamblee.system.components;
+
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.system.container.Container;
+
+public class DatabaseComponentFactory {
+
+    public static void addDatabaseConfig(Container aContainer) {
+        try {
+            aContainer.addComponent(new DatabaseComponent("db",
+                    DatabaseBuilder.getDatabase())); 
+        } catch (Exception e) {
+            throw new RuntimeException("Could not add database configuration",
+                    e);
+        }
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/container/Application.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/container/Application.java
new file mode 100644 (file)
index 0000000..9392974
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright 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.wamblee.system.container;
+
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.test.EventTracker;
+
+public class Application extends AbstractComponent<Object> {
+    public static RequiredInterface[] required(boolean aOptional,
+            String aPrefix) {
+        return new RequiredInterface[] {
+                new DefaultRequiredInterface(aPrefix + "string", String.class,
+                        aOptional),
+                new DefaultRequiredInterface(aPrefix + "integer",
+                        Integer.class, aOptional) };
+    }
+
+    public static RequiredInterface[] required(boolean aOptional) {
+        return required(aOptional, "");
+    }
+
+    private EventTracker<String> _tracker;
+    private String _string;
+    private Integer _integer;
+    private double _random;
+
+    public Application() {
+        this("application");
+    }
+
+    public Application(String aName) {
+        this(aName, "");
+    }
+
+    public Application(String aName, String aPrefix) {
+        super(aName, new ProvidedInterface[0], required(false,
+                aPrefix));
+        _random = Math.random();
+    }
+
+    public Application(boolean aIsOptinal) {
+        super("application", new ProvidedInterface[0], required(true, ""));
+    }
+
+    public Application(EventTracker<String> aTracker) {
+        this();
+        _tracker = aTracker;
+    }
+
+    @Override
+    public Object doStart(Scope aScope) {
+        track("start." + getName());
+        _string = aScope.getInterfaceImplementation(getRequiredInterfaces()
+                .get(0).getProvider(), String.class);
+        _integer = aScope.getInterfaceImplementation(getRequiredInterfaces()
+                .get(1).getProvider(), Integer.class);
+        return _random;
+    }
+
+    public String getString() {
+        return _string;
+    }
+
+    public Integer getInteger() {
+        return _integer;
+    }
+
+    @Override
+    public void doStop(Object aRuntime) {
+        track("stop." + getName());
+        if (_random != (Double) aRuntime) {
+            throw new IllegalArgumentException("Wrong runtime: expected "
+                    + _random + " but got " + aRuntime);
+        }
+    }
+
+    private void track(String aString) {
+        if (_tracker == null) {
+            return;
+        }
+        _tracker.eventOccurred(aString);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java
new file mode 100644 (file)
index 0000000..a7589fe
--- /dev/null
@@ -0,0 +1,745 @@
+/*
+ * Copyright 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.wamblee.system.container;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.wamblee.general.Pair;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.DefaultScope;
+import org.wamblee.system.core.Environment;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.StringComponent;
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.test.AssertionUtils;
+import org.wamblee.test.EventTracker;
+
+public class ContainerTest extends TestCase {
+
+       private EventTracker<String> _tracker;
+
+       @Override
+       protected void setUp() throws Exception {
+               super.setUp();
+               _tracker = new EventTracker<String>();
+       }
+
+       private static class MyMultiple implements Serializable, Runnable {
+               @Override
+               public void run() {
+                       // Empty
+               }
+       }
+
+       private List<Pair<ProvidedInterface, Component>> createProvidedInput(
+                       ProvidedInterface[] aProvided, Component aProvider) {
+               List<Pair<ProvidedInterface, Component>> result = new ArrayList<Pair<ProvidedInterface, Component>>();
+               for (ProvidedInterface provided : aProvided) {
+                       result.add(new Pair<ProvidedInterface, Component>(provided,
+                                       aProvider));
+               }
+               return result;
+       }
+
+       public void testEnvironmentApplication() {
+               Environment environment = new Environment(_tracker);
+               Application application = new Application(_tracker);
+               Container container = new Container("root", new Component[] {
+                               environment, application }, new ProvidedInterface[0],
+                               new RequiredInterface[0]);
+               Scope scope = container.start();
+               assertTrue(container.isSealed());
+               AssertionUtils.assertEquals(new String[] { "start.environment",
+                               "start.application" }, _tracker.getEvents(
+                               Thread.currentThread()).toArray(new String[0]));
+               assertEquals(0, scope.getProvidedInterfaces().size());
+
+               assertEquals(environment.getString(), application.getString());
+               assertEquals(environment.getInteger(), application.getInteger());
+
+       }
+
+       public void testEnvironmentApplicationSimpleConstructor() {
+               Environment environment = new Environment(_tracker);
+               Application application = new Application(_tracker);
+               Container container = new Container("root").addComponent(environment)
+                               .addComponent(application);
+
+               Scope scope = container.start();
+               AssertionUtils.assertEquals(new String[] { "start.environment",
+                               "start.application" }, _tracker.getEvents(
+                               Thread.currentThread()).toArray(new String[0]));
+               assertEquals(0, scope.getProvidedInterfaces().size());
+
+               assertEquals(environment.getString(), application.getString());
+               assertEquals(environment.getInteger(), application.getInteger());
+
+       }
+
+       public void testApplicationEnvironment() {
+               try {
+                       Component<?> environment = new Environment();
+                       Component<?> application = new Application();
+                       Container container = new Container("root", new Component[] {
+                                       application, environment }, new ProvidedInterface[0],
+                                       new RequiredInterface[0]);
+                       container.start();
+               } catch (SystemAssemblyException e) {
+                       // e.printStackTrace();
+                       return;
+               }
+               fail();
+       }
+
+       public void testComposite() {
+               Component<?> environment = new Environment(_tracker);
+               Component<?> application = new Application(_tracker);
+               assertEquals(0, _tracker.getEventCount());
+
+               Container system = new Container("all", new Component[] { environment,
+                               application }, new ProvidedInterface[0],
+                               new RequiredInterface[0]);
+               Scope runtime = system.start();
+               List<RequiredInterface> required = system.getRequiredInterfaces();
+               assertEquals(0, required.size());
+               List<ProvidedInterface> provided = system.getProvidedInterfaces();
+               assertEquals(0, provided.size());
+
+               AssertionUtils.assertEquals(new String[] { "start.environment",
+                               "start.application" }, _tracker.getEvents(
+                               Thread.currentThread()).toArray(new String[0]));
+               _tracker.clear();
+
+               system.stop(runtime);
+               AssertionUtils.assertEquals(new String[] { "stop.application",
+                               "stop.environment" }, _tracker
+                               .getEvents(Thread.currentThread()).toArray(new String[0]));
+
+       }
+
+       public void testCompositeWithWrongProvidedInfo() {
+               try {
+                       Component<?> environment = new Environment();
+                       Component<?> application = new Application();
+                       Container system = new Container("all", new Component[] {
+                                       environment, application },
+                                       new ProvidedInterface[] { new DefaultProvidedInterface(
+                                                       "float", Float.class) },
+                                       new DefaultRequiredInterface[0]);
+                       system.validate();
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testCompositeRequiredInterfaceNotProvided() {
+               try {
+                       Component<?> environment = new Environment();
+                       Component<?> application = new Application();
+                       Container system = new Container("all", new Component[] {
+                                       environment, application }, new ProvidedInterface[0],
+                                       new RequiredInterface[] { new DefaultRequiredInterface(
+                                                       "string", String.class) });
+                       system.start();
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testCompositeWithSuperfluousRequiredInfo() {
+               Component<?> environment = new Environment();
+               Component<?> application = new Application();
+               Container system = new Container("all", new Component[] { environment,
+                               application }, new ProvidedInterface[0],
+                               new RequiredInterface[] { new DefaultRequiredInterface("float",
+                                               Float.class) });
+               system.getRequiredInterfaces().get(0).setProvider(
+                               new DefaultProvidedInterface("hallo", Float.class));
+               system.start();
+               List<RequiredInterface> required = system.getRequiredInterfaces();
+               assertEquals(1, required.size());
+               List<ProvidedInterface> provided = system.getProvidedInterfaces();
+               assertEquals(0, provided.size());
+       }
+
+       public void testCompositeWithExternalDependencesNotProvided() {
+               try {
+                       Component<?> application = new Application();
+
+                       Container system = new Container("all",
+                                       new Component[] { application }, new ProvidedInterface[0],
+                                       application.getRequiredInterfaces().toArray(
+                                                       new RequiredInterface[0]));
+                       system.start();
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testDuplicateComponent() {
+               try {
+                       Component<?> comp1 = new Application();
+                       Component<?> comp2 = new Application();
+                       Container system = new Container("top");
+                       system.addComponent(comp1).addComponent(comp2);
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testInconsistentHierarchy() {
+               try {
+                       Component<?> comp = new Application();
+                       Container system = new Container("top").addComponent(comp);
+                       Container system2 = new Container("top2").addComponent(comp);
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testCompositeWithExternalDependencesProvided() {
+
+               Component<?> environment = new Environment();
+               Component<?> application = new Application();
+               Container system = new Container("all",
+                               new Component[] { application }, new ProvidedInterface[0],
+                               application.getRequiredInterfaces().toArray(
+                                               new RequiredInterface[0]));
+               environment.start(new DefaultScope(new ProvidedInterface[0]));
+               system.getRequiredInterfaces().get(0).setProvider(
+                               environment.getProvidedInterfaces().get(0));
+               system.getRequiredInterfaces().get(1).setProvider(
+                               environment.getProvidedInterfaces().get(1));
+
+               system.start();
+               List<RequiredInterface> required = system.getRequiredInterfaces();
+               assertEquals(2, required.size());
+               List<ProvidedInterface> provided = system.getProvidedInterfaces();
+               assertEquals(0, provided.size());
+
+       }
+
+       public void testAmbiguousInterfaces() {
+               try {
+                       Component<?> environment1 = new Environment();
+                       Component<?> environment2 = new Environment();
+                       Component<?> application = new Application();
+                       Container container = new Container("root", new Component[] {
+                                       environment1, environment2, application },
+                                       new ProvidedInterface[0], new RequiredInterface[0]);
+                       container.start();
+
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testIncompleteRequirements() {
+               try {
+                       Component<?> application = new Application();
+                       Container system = new Container("all",
+                                       new Component[] { application }, new ProvidedInterface[0],
+                                       new RequiredInterface[0]);
+                       system.start();
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testEnvironmentApplicationRollbackOnException()
+                       throws Exception {
+               Environment environment = new Environment(_tracker);
+               Application application = new Application() { 
+                       @Override
+                       public Object doStart(Scope aScope) {
+                               throw new RuntimeException();
+                       }
+               };
+               
+               try {
+                       Container container = new Container("root", new Component[] {
+                                       environment, application }, new ProvidedInterface[0],
+                                       new RequiredInterface[0]);
+
+                       container.start();
+               } catch (RuntimeException e) {
+                       AssertionUtils.assertEquals(new String[] { "start.environment",
+                                       "stop.environment" }, _tracker.getEvents(
+                                       Thread.currentThread()).toArray(new String[0]));
+                       return;
+               }
+               fail();
+       }
+
+       public void testEnvironmentApplicationRollbackOnExceptionWithExceptionOnStop()
+                       throws Exception {
+
+               Environment environment = new Environment(_tracker);
+               // Application 1 will throw an exception while stopping.
+               Application application1 = new Application("app1")  {
+                       @Override
+                       public void doStop(Object aRuntime) {
+                               throw new RuntimeException();
+                       }
+               };
+
+               // application 2 will throw an exception while starting
+               Application application2 = new Application("app2") {
+                       public Object doStart(Scope aScope) { 
+                               throw new RuntimeException();
+                       }
+               };
+
+               try {
+                       Container container = new Container("root", new Component[] {
+                                       environment, application1, application2 },
+                                       new ProvidedInterface[0], new RequiredInterface[0]);
+
+                       container.start();
+               } catch (RuntimeException e) {
+                       AssertionUtils.assertEquals(new String[] { "start.environment",
+                                       "stop.environment" }, _tracker.getEvents(
+                                       Thread.currentThread()).toArray(new String[0]));
+                       return;
+               }
+               fail();
+       }
+
+       public void testOptionalRequiredInterfaceProvidedOptionalInternal() {
+               Application application = new Application(true);
+               Container container = new Container("top",
+                               new Component[] { application }, new ProvidedInterface[0],
+                               Application.required(true));
+               Environment env = new Environment();
+               container.getRequiredInterfaces().get(0).setProvider(
+                               env.getProvidedInterfaces().get(0));
+               container.getRequiredInterfaces().get(1).setProvider(
+                               env.getProvidedInterfaces().get(1));
+               Scope external = new DefaultScope(env.getProvidedInterfaces());
+               env.start(external);
+
+               container.start(external);
+               assertSame(env.getProvidedInterfaces().get(0), container
+                               .getRequiredInterfaces().get(0).getProvider());
+               assertSame(env.getProvidedInterfaces().get(1), container
+                               .getRequiredInterfaces().get(1).getProvider());
+               assertSame(env.getProvidedInterfaces().get(0), application
+                               .getRequiredInterfaces().get(0).getProvider());
+               assertSame(env.getProvidedInterfaces().get(1), application
+                               .getRequiredInterfaces().get(1).getProvider());
+       }
+
+       public void testOptionalRequiredInterfaceNotProvidedOptionalInternal() {
+               Application application = new Application(true);
+               Container container = new Container("top",
+                               new Component[] { application }, new ProvidedInterface[0],
+                               Application.required(true));
+               Environment env = new Environment();
+               container.getRequiredInterfaces().get(0).setProvider(
+                               env.getProvidedInterfaces().get(0));
+               Scope external = new DefaultScope(new ProvidedInterface[0]);
+               external.publishInterface(env.getProvidedInterfaces().get(0), env
+                               .getString());
+               container.start(external);
+               assertSame(env.getProvidedInterfaces().get(0), container
+                               .getRequiredInterfaces().get(0).getProvider());
+               assertNull(container.getRequiredInterfaces().get(1).getProvider());
+               assertSame(env.getProvidedInterfaces().get(0), application
+                               .getRequiredInterfaces().get(0).getProvider());
+               assertNull(application.getRequiredInterfaces().get(1).getProvider());
+       }
+
+       public void testOptionalRequiredInterfaceProvidedMandatoryInternal() {
+               Application application = new Application();
+               Container container = new Container("top",
+                               new Component[] { application }, new ProvidedInterface[0],
+                               Application.required(true));
+               Environment env = new Environment();
+               container.getRequiredInterfaces().get(0).setProvider(
+                               env.getProvidedInterfaces().get(0));
+               container.getRequiredInterfaces().get(1).setProvider(
+                               env.getProvidedInterfaces().get(1));
+               try {
+                       container.start();
+               } catch (SystemAssemblyException e) {
+                       return;
+               }
+               fail();
+       }
+
+       public void testSealed() {
+               final Container container = new Container("xx");
+               assertFalse(container.isSealed());
+               container.start();
+               assertTrue(container.isSealed());
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.addComponent(new Application());
+                       }
+               }, SystemAssemblyException.class);
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectRequiredProvided("x", "y", "a", "b");
+                       }
+               }, SystemAssemblyException.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalRequired("x", "y", "a");
+                       }
+               }, SystemAssemblyException.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalProvided("x", "y", "z");
+                       }
+               }, SystemAssemblyException.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.addProvidedInterface(new DefaultProvidedInterface(
+                                               "xx", String.class));
+                       }
+               }, SystemAssemblyException.class);
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.addRequiredInterface(new DefaultRequiredInterface(
+                                               "xx", String.class));
+                       }
+               }, SystemAssemblyException.class);
+       }
+
+       public void testRestriction() {
+               Environment env1 = new Environment("env1");
+               Environment env2 = new Environment("env2");
+               Application app = new Application("app");
+               Container container = new Container("top").addComponent(env1)
+                               .addComponent(env2).addComponent(app);
+               container.connectRequiredProvided("app", null, "env1", null);
+               container.start();
+               assertEquals(env1.getString(), app.getString());
+               assertEquals(env1.getInteger(), app.getInteger());
+               assertFalse(env2.getString().equals(app.getString()));
+               assertFalse(env2.getInteger().equals(app.getInteger()));
+       }
+
+       public void testRestrictionWithFromAndToInterfaceName() {
+               Environment env1 = new Environment("env1");
+               Environment env2 = new Environment("env2");
+               Application app = new Application("app");
+               Container container = new Container("top").addComponent(env1)
+                               .addComponent(env2).addComponent(app);
+               container.connectRequiredProvided("app", app.getRequiredInterfaces()
+                               .get(0).getName(), "env1", env1.getProvidedInterfaces().get(0)
+                               .getName());
+               container.connectRequiredProvided("app", app.getRequiredInterfaces()
+                               .get(1).getName(), "env2", env2.getProvidedInterfaces().get(1)
+                               .getName());
+               container.start();
+               assertEquals(env1.getString(), app.getString());
+               assertEquals(env2.getInteger(), app.getInteger());
+               assertFalse(env2.getString().equals(app.getString()));
+               assertFalse(env1.getInteger().equals(app.getInteger()));
+       }
+
+       public void testRestrictionWrongComponentNames() {
+               Environment env1 = new Environment("env1");
+               Environment env2 = new Environment("env2");
+               Application app = new Application("app");
+               final Container container = new Container("top").addComponent(env1)
+                               .addComponent(env2).addComponent(app);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectRequiredProvided("app2", null, "env1", null);
+                       }
+               }, SystemAssemblyException.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectRequiredProvided("app", null, "env3", null);
+                       }
+               }, SystemAssemblyException.class);
+       }
+
+       public void testRestrictionWrongInterfaceNames() {
+               final Environment env1 = new Environment("env1");
+               Environment env2 = new Environment("env2");
+               final Application app = new Application("app");
+               final Container container = new Container("top").addComponent(env1)
+                               .addComponent(env2).addComponent(app);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectRequiredProvided("app", app
+                                               .getRequiredInterfaces().get(0).getName()
+                                               + "xxx", "env1", null);
+                       }
+               }, SystemAssemblyException.class);
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectRequiredProvided("app", null, "env1", env1
+                                               .getProvidedInterfaces().get(0).getName()
+                                               + "yyy");
+                       }
+               }, SystemAssemblyException.class);
+       }
+
+       public void testProvidedInDifferentScopes() {
+               // Scoping problem occurred. Externally and internally provided
+               // components clashed
+               // because unique id generation in the scope was wrong.
+
+               StringComponent str = new StringComponent("string");
+               Application app = new Application("app");
+               Container container = new Container("top").addComponent(str)
+                               .addComponent(app);
+               container.addRequiredInterface(new DefaultRequiredInterface("integer",
+                               Integer.class));
+
+               ProvidedInterface provided = new DefaultProvidedInterface("hallo",
+                               Integer.class);
+               container.getRequiredInterfaces().get(0).setProvider(provided);
+
+               Scope external = new DefaultScope(new ProvidedInterface[0]);
+               external.publishInterface(provided, 100);
+               Scope scope = container.start(external);
+       }
+
+       public void testProvidedInterfaces() {
+               Environment env = new Environment(_tracker);
+               Container envcontainer = new Container("0").addComponent(env)
+                               .addProvidedInterface(
+                                               new DefaultProvidedInterface("string", String.class))
+                               .addProvidedInterface(
+                                               new DefaultProvidedInterface("integer", Integer.class));
+               Scope scope = envcontainer.start();
+
+               AssertionUtils.assertEquals(new String[] { "start.environment" },
+                               _tracker.getEvents(Thread.currentThread()).toArray(
+                                               new String[0]));
+
+               envcontainer.stop(scope);
+       }
+
+       public void testCoupleTwoContainers() {
+               Environment env = new Environment(_tracker);
+               Container envcontainer = new Container("0").addComponent(env)
+                               .addProvidedInterface(
+                                               new DefaultProvidedInterface("string", String.class))
+                               .addProvidedInterface(
+                                               new DefaultProvidedInterface("integer", Integer.class));
+
+               Application app = new Application(_tracker);
+               Container appcontainer = new Container("1").addComponent(app)
+                               .addRequiredInterface(
+                                               new DefaultRequiredInterface("string", String.class))
+                               .addRequiredInterface(
+                                               new DefaultRequiredInterface("integer", Integer.class));
+
+               Container top = new Container("top");
+               top.addComponent(envcontainer).addComponent(appcontainer);
+
+               top.start();
+               AssertionUtils.assertEquals(new String[] { "start.environment",
+                               "start.application" }, _tracker.getEvents(
+                               Thread.currentThread()).toArray(new String[0]));
+
+       }
+
+       public void testNonUniqueRequiredInterface() {
+               final Container container = new Container("top");
+               container.addRequiredInterface(new DefaultRequiredInterface("i",
+                               Integer.class));
+               container.addRequiredInterface(new DefaultRequiredInterface("x",
+                               String.class));
+               container.addRequiredInterface(new DefaultRequiredInterface("y",
+                               String.class));
+
+               Application app = new Application("1");
+               container.addComponent(app);
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.start();
+                       }
+               }, SystemAssemblyException.class);
+
+               container.connectExternalRequired("1", app.getRequiredInterfaces().get(
+                               0).getName(), "y");
+
+               ProvidedInterface i = new DefaultProvidedInterface("i", Integer.class);
+               ProvidedInterface x = new DefaultProvidedInterface("x", String.class);
+               ProvidedInterface y = new DefaultProvidedInterface("y", String.class);
+
+               Scope externalScope = new DefaultScope(new ProvidedInterface[0]);
+
+               externalScope.publishInterface(i, 100);
+               externalScope.publishInterface(x, "x-value");
+               externalScope.publishInterface(y, "y-value");
+
+               container.getRequiredInterfaces().get(0).setProvider(i);
+               container.getRequiredInterfaces().get(1).setProvider(x);
+               container.getRequiredInterfaces().get(2).setProvider(y);
+
+               Scope runtime = container.start(externalScope);
+
+               assertEquals("y-value", app.getString());
+
+       }
+
+       public void testNonUniqueRequiredInterfaceWrongNames() {
+               final Container container = new Container("top");
+               container.addRequiredInterface(new DefaultRequiredInterface("i",
+                               Integer.class));
+               container.addRequiredInterface(new DefaultRequiredInterface("x",
+                               String.class));
+               container.addRequiredInterface(new DefaultRequiredInterface("y",
+                               String.class));
+
+               final Application app = new Application("1");
+               container.addComponent(app);
+
+               // wrong component name.
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalRequired("2", "x", "y");
+                       }
+               }, SystemAssemblyException.class);
+
+               // Wrong interface name of component.
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalRequired("1", app
+                                               .getRequiredInterfaces().get(0).getName()
+                                               + "xxx", "y");
+                       }
+               }, SystemAssemblyException.class);
+
+               // Wrong external interface name of container
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalRequired("1", app
+                                               .getRequiredInterfaces().get(0).getName(), "z");
+                       }
+               }, SystemAssemblyException.class);
+       }
+
+       public void testNonUniqueProvidedInterface() {
+
+               final Container container = new Container("top")
+                               .addProvidedInterface(new DefaultProvidedInterface("external",
+                                               String.class));
+               Environment env1 = new Environment("env1");
+               Environment env2 = new Environment("env2");
+
+               container.addComponent(env1);
+               container.addComponent(env2);
+
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.start();
+                       }
+               }, SystemAssemblyException.class);
+
+               // now choose env2
+
+               container.connectExternalProvided(container.getProvidedInterfaces()
+                               .get(0).getName(), env2.getName(), env2.getProvidedInterfaces()
+                               .get(0).getName());
+
+               Scope scope = container.start();
+
+               // check the value of the provided interface of the container
+
+               String value = scope.getInterfaceImplementation(container
+                               .getProvidedInterfaces().get(0), String.class);
+               assertNotNull(value);
+               assertEquals(value, env2.getString());
+               assertFalse(value.equals(env1.getString()));
+       }
+
+       public void testNonUniqueProvidedInterfaceWrongNames() {
+
+               final Container container = new Container("top")
+                               .addProvidedInterface(new DefaultProvidedInterface("external",
+                                               String.class));
+               final Environment env1 = new Environment("env1");
+               final Environment env2 = new Environment("env2");
+
+               container.addComponent(env1);
+               container.addComponent(env2);
+
+               // Wrong external provided interface name
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalProvided(container
+                                               .getProvidedInterfaces().get(0).getName()
+                                               + "xx", "env1", env1.getProvidedInterfaces().get(0)
+                                               .getName());
+                       }
+               }, SystemAssemblyException.class);
+
+               // Wrong provided interface name.
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalProvided(container
+                                               .getProvidedInterfaces().get(0).getName(), "env1", env1
+                                               .getProvidedInterfaces().get(0).getName()
+                                               + "xx");
+                       }
+               }, SystemAssemblyException.class);
+
+               // Wrong provided component
+               AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+                       @Override
+                       public void run() throws Exception {
+                               container.connectExternalProvided(container
+                                               .getProvidedInterfaces().get(0).getName(), "env3", env1
+                                               .getProvidedInterfaces().get(0).getName());
+                       }
+               }, SystemAssemblyException.class);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java
new file mode 100644 (file)
index 0000000..2fd48f6
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import junit.framework.TestCase;
+
+public class AbstractComponentTest extends TestCase {
+
+       public void testNotAllInterfacesStarted() {
+               try {
+                       Component<?> component = new AbstractComponent<Object>("xx",
+                                       new ProvidedInterface[] { new DefaultProvidedInterface(
+                                                       "xxx", String.class) }, new RequiredInterface[0]) {
+                               @Override
+                               protected Object doStart(Scope aScope) {
+                                       // Empty, not starting service.
+                                       return null; 
+                               }
+
+                               @Override
+                               protected void doStop(Object aRuntime) {
+                                       // Empty.
+                               }
+                       };
+                       component.start(new DefaultScope(component.getProvidedInterfaces()));
+               } catch (SystemAssemblyException e) {
+                       //e.printStackTrace();
+                       return;
+               }
+               fail();
+       }
+       
+       public void testUnexpectedServicesStarted() { 
+           try {
+            Component<?> component = new AbstractComponent<Object>("xx",
+                    new ProvidedInterface[0], new RequiredInterface[0]) {
+                @Override
+                protected Object doStart(Scope aScope) {
+                    addInterface(new DefaultProvidedInterface("x", Integer.class), 100, aScope);
+                    return null; 
+                }
+
+                @Override
+                protected void doStop(Object aRuntime) {
+                    // Empty.
+                }
+            };
+            component.start(new DefaultScope(component.getProvidedInterfaces()));
+        } catch (SystemAssemblyException e) {
+            //e.printStackTrace();
+            return;
+        }
+        fail();
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java
new file mode 100644 (file)
index 0000000..5bfca07
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.io.Serializable;
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+
+import junit.framework.TestCase;
+
+public class DefaultInterfaceDescriptorTest extends TestCase {
+
+       public void testOneRequiredOneProvidedMatch() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", String.class);
+               RequiredInterface required = new DefaultRequiredInterface("name", String.class);
+               assertTrue(required.implementedBy(provided));
+       }
+       
+       public void testOneRequiredOneProvidedMatchSubClass() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", Integer.class);
+               RequiredInterface required = new DefaultRequiredInterface("name", Number.class);
+               assertTrue(required.implementedBy(provided));
+       }
+       
+       public void testOneRequiredOneProvidedNoMatch() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", String.class);
+               RequiredInterface required = new DefaultRequiredInterface("name", Number.class);
+               assertFalse(required.implementedBy(provided));
+       }
+       
+       public void testOneRequiredMultipleProvidedMatch() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", 
+                               new Class[] { String.class, Integer.class} );
+               RequiredInterface required = new DefaultRequiredInterface("name", String.class);
+               assertTrue(required.implementedBy(provided));
+       }
+       
+       private static class MyMultiple implements Runnable, Serializable { 
+               @Override
+               public void run() {
+                       // Empty        
+               }
+       }
+       
+       public void testMultipleRequiredOneProvidedMatch() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", 
+                               MyMultiple.class );
+               RequiredInterface required = new DefaultRequiredInterface("name", 
+                               new Class[] {Runnable.class, Serializable.class} );
+               assertTrue(required.implementedBy(provided));
+       }
+       
+       public void testMultipleRequiredOneProvidedNoMatch() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", 
+                               MyMultiple.class );
+               RequiredInterface required = new DefaultRequiredInterface("name", 
+                               new Class[] { String.class, Runnable.class} );
+               assertFalse(required.implementedBy(provided));
+       }
+       
+       public void testMultipleRequiredMultipleProvidedMatch() { 
+               ProvidedInterface provided = new DefaultProvidedInterface("name", 
+                               new Class[] { Runnable.class, Serializable.class, String.class}  );
+               RequiredInterface required = new DefaultRequiredInterface("name", 
+                               new Class[] {Runnable.class, Serializable.class} );
+               assertTrue(required.implementedBy(provided));
+       }
+       
+       public void testPrimitiveAndWrapperType() { 
+               RequiredInterface req1 = new DefaultRequiredInterface("req1", int.class);
+               RequiredInterface req2 = new DefaultRequiredInterface("req1", Integer.class);
+               ProvidedInterface prov1 = new DefaultProvidedInterface("prov1", int.class);
+               ProvidedInterface prov2 = new DefaultProvidedInterface("prov2", Integer.class);
+               assertTrue(req1.implementedBy(prov1));
+               assertTrue(req2.implementedBy(prov1));
+               assertTrue(req1.implementedBy(prov2));
+               assertTrue(req2.implementedBy(prov2));
+       }
+       
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java
new file mode 100644 (file)
index 0000000..139de7d
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import junit.framework.TestCase;
+
+public class DefaultRequiredInterfaceTest extends TestCase {
+
+    public void testEquals() {
+        assertFalse(new DefaultRequiredInterface("a", String.class)
+                .equals(new DefaultRequiredInterface("a", String.class)));
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java
new file mode 100644 (file)
index 0000000..7199c6f
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import junit.framework.TestCase;
+
+public class DefaultScopeTest extends TestCase {
+    
+    public void testLookup() { 
+        ProvidedInterface provider = new DefaultProvidedInterface("x", Integer.class);
+        Scope scope = new DefaultScope(new ProvidedInterface[0]); 
+         
+        scope.publishInterface(provider, 100);
+        assertEquals(100, scope.getInterfaceImplementation(provider, Integer.class).intValue());
+    }
+    
+    public void testNestedLookup() { 
+        ProvidedInterface provider1 = new DefaultProvidedInterface("x", Integer.class);
+        Scope parent = new DefaultScope(new ProvidedInterface[0]);
+        
+        parent.publishInterface(provider1, 100);
+        
+        ProvidedInterface provider2 = new DefaultProvidedInterface("y", String.class);
+        Scope child = new DefaultScope(new ProvidedInterface[0], parent);
+        
+        child.publishInterface(provider2, "hallo");
+        
+        assertFalse(provider1.equals(provider2));
+        assertEquals(100, child.getInterfaceImplementation(provider1, Integer.class).intValue());
+        assertEquals("hallo", child.getInterfaceImplementation(provider2, String.class));
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/Environment.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/Environment.java
new file mode 100644 (file)
index 0000000..4b791d0
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import javax.sql.DataSource;
+
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.test.EventTracker;
+
+public class Environment extends AbstractComponent<Object> {
+
+       private static final ProvidedInterface[] provided(String aPrefix) {
+               return new ProvidedInterface[] {
+                               new DefaultProvidedInterface(aPrefix + "datasource", String.class),
+                               new DefaultProvidedInterface(aPrefix + "integer", Integer.class) };
+       }
+       
+       private static int COUNT = 0; 
+
+       private EventTracker<String> _tracker;
+       private double _random;
+       private int _integer; 
+
+       public Environment() {
+               this("environment");
+       }
+       
+       public Environment(String aName) {
+       this(aName, "");
+    }
+       
+       public Environment(String aName, String aPrefix) {
+        super(aName, provided(aPrefix), new RequiredInterface[0]);
+        _random = Math.random();
+        _integer = COUNT++;
+    }
+
+
+
+       public Environment(EventTracker aTracker) {
+               this();
+               _tracker = aTracker;
+       }
+
+       public Integer getInteger() {
+               return _integer;
+       }
+
+       public String getString() {
+               return getName() + ".hello";
+       }
+
+       @Override
+       protected Object doStart(Scope aScope) {
+               addInterface(getProvidedInterfaces().get(0), getString(), aScope);
+               addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
+               track("start." + getName());
+               return _random;
+       }
+
+       @Override
+       protected void doStop(Object aRuntime) {
+               track("stop." + getName());
+               if (_random != (Double) aRuntime) {
+                       throw new IllegalArgumentException("Wrong runtime: expected "
+                                       + _random + " but got " + aRuntime);
+               }
+       }
+
+       private void track(String aString) {
+               if (_tracker == null) {
+                       return;
+               }
+               _tracker.eventOccurred(aString);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java
new file mode 100644 (file)
index 0000000..acf683f
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import javax.sql.DataSource;
+
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.test.EventTracker;
+
+public class IntegerComponent extends AbstractComponent<Object> {
+
+       private static final ProvidedInterface[] provided(String aPrefix) {
+               return new ProvidedInterface[] {
+                               new DefaultProvidedInterface(aPrefix + "integer", Integer.class) };
+       }
+
+       private EventTracker<String> _tracker;
+       private double _random;
+
+       public IntegerComponent() {
+               this("environment");
+       }
+       
+       public IntegerComponent(String aName) {
+       this(aName, "");
+    }
+       
+       public IntegerComponent(String aName, String aPrefix) {
+        super(aName, provided(aPrefix), new RequiredInterface[0]);
+        _random = Math.random();
+    }
+
+
+
+       public IntegerComponent(EventTracker aTracker) {
+               this();
+               _tracker = aTracker;
+       }
+
+       public Integer getInteger() {
+               return 2;
+       }
+
+       @Override
+       protected Object doStart(Scope aScope) {
+               addInterface(getProvidedInterfaces().get(1), getInteger(), aScope);
+               track("start." + getName());
+               return _random;
+       }
+
+       @Override
+       protected void doStop(Object aRuntime) {
+               track("stop." + getName());
+               if (_random != (Double) aRuntime) {
+                       throw new IllegalArgumentException("Wrong runtime: expected "
+                                       + _random + " but got " + aRuntime);
+               }
+       }
+
+       private void track(String aString) {
+               if (_tracker == null) {
+                       return;
+               }
+               _tracker.eventOccurred(aString);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java
new file mode 100644 (file)
index 0000000..404fec7
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import java.util.Comparator;
+
+public class RequiredInterfaceComparator implements
+        Comparator<RequiredInterface> {
+
+    @Override
+    public int compare(RequiredInterface aO1, RequiredInterface aO2) {
+        return aO1.getName().compareTo(aO2.getName());
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/StringComponent.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/core/StringComponent.java
new file mode 100644 (file)
index 0000000..7701c20
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright 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.wamblee.system.core;
+
+import javax.sql.DataSource;
+
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.test.EventTracker;
+
+public class StringComponent extends AbstractComponent<Object> {
+
+       private static final ProvidedInterface[] provided(String aPrefix) {
+               return new ProvidedInterface[] {
+                               new DefaultProvidedInterface(aPrefix + "datasource", String.class) };
+       }
+
+       private EventTracker<String> _tracker;
+       private double _random;
+
+       public StringComponent() {
+               this("environment");
+       }
+       
+       public StringComponent(String aName) {
+       this(aName, "");
+    }
+       
+       public StringComponent(String aName, String aPrefix) {
+        super(aName, provided(aPrefix), new RequiredInterface[0]);
+        _random = Math.random();
+    }
+
+
+
+       public StringComponent(EventTracker aTracker) {
+               this();
+               _tracker = aTracker;
+       }
+
+       public Integer getInteger() {
+               return 2;
+       }
+
+       public String getString() {
+               return getName() + ".hello";
+       }
+
+       @Override
+       protected Object doStart(Scope aScope) {
+               addInterface(getProvidedInterfaces().get(0), getString(), aScope);
+               track("start." + getName());
+               return _random;
+       }
+
+       @Override
+       protected void doStop(Object aRuntime) {
+               track("stop." + getName());
+               if (_random != (Double) aRuntime) {
+                       throw new IllegalArgumentException("Wrong runtime: expected "
+                                       + _random + " but got " + aRuntime);
+               }
+       }
+
+       private void track(String aString) {
+               if (_tracker == null) {
+                       return;
+               }
+               _tracker.eventOccurred(aString);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java
new file mode 100644 (file)
index 0000000..c76ff97
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
+import junit.framework.TestCase;
+
+import org.wamblee.system.container.Application;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.Environment;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.graph.component.ProvidedInterfaceNode;
+import org.wamblee.system.graph.component.RequiredInterfaceNode;
+
+public class CompositeEdgeFilterTest extends TestCase {
+    private Application _app = new Application(); 
+    private Environment _env = new Environment();
+    
+    private Edge createEdge(Component aClient, RequiredInterface aRequired, 
+            Component aServer, ProvidedInterface aProvided) { 
+        Node from = new RequiredInterfaceNode(aClient, aRequired);
+        Node to = new ProvidedInterfaceNode(aServer, aProvided);
+        return new DefaultEdge(from, to);
+    }
+
+    public void testEmpty() { 
+        EdgeFilter restriction = new CompositeEdgeFilter(); 
+        assertFalse(restriction.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
+                _env, _env.getProvidedInterfaces().get(0))));
+    }
+    
+    private void configureRestriction(EdgeFilter base, boolean aResult) {
+       stub(base.isViolated((Edge)anyObject())).toReturn(aResult);
+    }
+    
+    public void testOneRestriction() { 
+        EdgeFilter base = mock(EdgeFilter.class);
+        CompositeEdgeFilter composite = new CompositeEdgeFilter();
+        composite.add(base);
+        
+        // First let the base return false and verify the result. 
+        
+        configureRestriction(base, false);
+        
+        assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
+                _env, _env.getProvidedInterfaces().get(0))));
+        
+        // Second let the base return true and verify the result.
+        configureRestriction(base, true);
+        
+        assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
+                _env, _env.getProvidedInterfaces().get(0))));
+    }
+
+   
+    
+    public void testTwoRestrictions() { 
+        EdgeFilter base1 = mock(EdgeFilter.class);
+        CompositeEdgeFilter composite = new CompositeEdgeFilter();
+        composite.add(base1);
+        EdgeFilter base2 = mock(EdgeFilter.class);
+        composite.add(base2);
+        
+        // 1. base1 not violated and base 2 not violated -> not violated. 
+        
+        configureRestriction(base1, false);
+        configureRestriction(base2, false);
+        assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
+                _env, _env.getProvidedInterfaces().get(0))));
+        
+        // 2. base 1 not violated but base 2 violated -> violated
+        configureRestriction(base1, false);
+        configureRestriction(base2, true);
+       
+        assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
+                _env, _env.getProvidedInterfaces().get(0))));
+     
+        // 3. base 1 violated -> violated and base 2 not called. 
+        configureRestriction(base1, true);
+        // base 2 should not be called.
+      
+        assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
+                _env, _env.getProvidedInterfaces().get(0))));
+    }
+    
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java
new file mode 100644 (file)
index 0000000..675a06b
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.Mockito.*;
+import org.wamblee.test.AssertionUtils;
+
+
+import junit.framework.TestCase;
+
+public class GraphTest extends TestCase {
+
+    public void testNodeMgt() {
+        final Graph graph = new Graph();
+        assertTrue(graph.getNodes().isEmpty());
+        assertTrue(graph.getEdges().isEmpty());
+
+        final Node x = new DefaultNode("x");
+        graph.addNode(x);
+        assertEquals(Arrays.asList(new Node[] { x }), graph.getNodes());
+        assertSame(x, graph.findNode("x"));
+        assertNull(graph.findNode("y"));
+
+        assertTrue(graph.removeNode(x));
+        assertTrue(graph.getNodes().isEmpty());
+
+        // Empty node set. 
+        assertFalse(graph.removeNode(x));
+        
+        Node y = new DefaultNode("y"); 
+        graph.addNodes(Arrays.asList(new Node[] { x, y} ));
+        assertEquals(2, graph.getNodes().size());
+        
+        // duplicate node
+        AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { 
+            @Override
+            public void run() throws Exception {
+                graph.addNode(new DefaultNode("x"));   
+            }
+        }, IllegalArgumentException.class);
+    }
+
+    public void testEdgeMgt() { 
+        final Graph graph = new Graph();
+        final Node x = new DefaultNode("x"); 
+        final Node y = new DefaultNode("y"); 
+        graph.addNode(x);
+        graph.addNode(y);
+        final Edge e = new DefaultEdge(x, y); 
+        graph.addEdge(e);
+        assertEquals(Arrays.asList(new Edge[] { e }), graph.getEdges());
+        
+        // duplicate edge.
+        AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { 
+            @Override
+            public void run() throws Exception {
+                graph.addEdge(e);   
+            }
+        }, IllegalArgumentException.class);
+        
+        // Remove node when edge is still present
+        AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { 
+            @Override
+            public void run() throws Exception {
+                graph.removeNode(x);
+            }
+        }, IllegalArgumentException.class);
+        
+        
+        Node a = new DefaultNode("a");
+        graph.addNode(a);
+        graph.addEdges(Arrays.asList(new Edge[] { new DefaultEdge(x, a), new DefaultEdge(y, a) }));
+        assertEquals(3, graph.getEdges().size());
+    }
+    
+    public void testExtend() { 
+        Graph graph = new Graph(); 
+        graph.addNode(new MyNode("x", new String[] { "a", "b"}));
+        graph.addNode(new MyNode("y", new String[] { "b", "c"}));
+        graph.addNode(new MyNode("z", new String[] { "a", "c"}));
+        graph.extend(new MyEdgeFactory());
+        
+        List<Edge> edges = graph.getEdges(); 
+        assertEquals(12, edges.size()); // 2 outgoing and 2 incoming nodes.
+    }
+    
+    public void testApplyFilter() { 
+        Graph graph = new Graph(); 
+        graph.addNode(new DefaultNode("x"));
+        graph.addNode(new DefaultNode("y"));
+        graph.addNode(new DefaultNode("z"));
+        graph.addEdge(new DefaultEdge(graph.findNode("x"), graph.findNode("y")));
+        graph.addEdge(new DefaultEdge(graph.findNode("y"), graph.findNode("z")));
+        graph.addEdge(new DefaultEdge(graph.findNode("z"), graph.findNode("x")));
+        
+        assertEquals(3, graph.getEdges().size());
+        
+        graph.applyFilter(new EdgeFilter() { 
+            @Override
+            public boolean isViolated(Edge aEdge) {
+                if (aEdge.getFrom().getName().equals("x")) { 
+                    return false; 
+                }
+                return true; 
+            }
+        }); 
+        
+        assertEquals(1, graph.getEdges().size());
+        assertEquals("x", graph.getEdges().get(0).getFrom().getName());
+           
+    }
+    
+    public void testFindIncomingOutgoing() { 
+        Graph graph = new Graph();
+        Node x = new DefaultNode("x");
+        Node y = new DefaultNode("y"); 
+        graph.addNode(x);
+        graph.addNode(y);
+        Edge e = new DefaultEdge(x,y);
+        graph.addEdge(e);
+        
+        List<Edge> incoming = graph.findIncoming(x);
+        assertTrue(incoming.isEmpty()); 
+        List<Edge> outgoing = graph.findOutgoing(x);
+        assertEquals(1, outgoing.size());
+        assertSame(e, outgoing.get(0));
+        
+        incoming = graph.findIncoming(y);
+        assertEquals(1, incoming.size());
+        assertSame(e, incoming.get(0));
+           
+        outgoing = graph.findOutgoing(y);
+        assertTrue(outgoing.isEmpty()); 
+    }
+    
+    public void testAccept() {
+        Graph graph = new Graph(); 
+        Node x = new DefaultNode("x"); 
+        Node y = new DefaultNode("y"); 
+        Edge e = new DefaultEdge(x, y);
+        graph.addNode(x);
+        graph.addNode(y);
+        graph.addEdge(e);
+        Visitor visitor = mock(Visitor.class); 
+        
+        graph.accept(visitor);
+        verify(visitor).visitNode(x);
+        verify(visitor).visitNode(y);
+        verify(visitor).visitEdge(e);
+        
+        verifyNoMoreInteractions(visitor);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java
new file mode 100644 (file)
index 0000000..daddccd
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MyEdgeFactory implements EdgeFactory<MyNode> {
+    
+    public MyEdgeFactory() { 
+        // Empty.
+    }
+
+    @Override
+    public List<Edge> create(MyNode aFrom, MyNode aTo) {
+        List<Edge> result = new ArrayList<Edge>();
+        for (String fromPort: aFrom.getPorts()) { 
+            for (String toPort: aTo.getPorts()) { 
+                if ( fromPort.equals(toPort)) { 
+                    result.add(new DefaultEdge(aFrom, aTo));
+                }
+            }
+        }
+        
+        return result; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/MyNode.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/MyNode.java
new file mode 100644 (file)
index 0000000..0090c3f
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.system.graph;
+
+public class MyNode extends DefaultNode {
+
+    private String[] _ports;   
+    
+    public MyNode(String aName, String[] aPorts) {
+        super(aName);
+        _ports = aPorts; 
+    }
+    
+    public String[] getPorts() {
+        return _ports;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java
new file mode 100644 (file)
index 0000000..5f45f55
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import junit.framework.TestCase;
+
+import org.wamblee.system.container.Container;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.Environment;
+import org.wamblee.system.graph.DefaultEdge;
+import org.wamblee.system.graph.DefaultNode;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFilter;
+
+public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase {
+
+    private Container _container;
+    private Component<Object> _internal;
+    private String _externalInterfaceName;
+    private String _internalComponentName;
+    private String _internalInterfaceName;
+    private Edge _edge;
+
+    @Override
+    protected void setUp() throws Exception {
+        _container = new Container("container")
+                .addProvidedInterface(new DefaultProvidedInterface("string",
+                        String.class));
+        _internal = new Environment("env1");
+
+        _externalInterfaceName = _container.getProvidedInterfaces().get(0)
+                .getName();
+        _internalComponentName = _internal.getName();
+        _internalInterfaceName = _internal.getProvidedInterfaces().get(0).getName();
+
+        _edge = new DefaultEdge(new ExternalProvidedInterfaceNode(_container,
+                _container.getProvidedInterfaces().get(0)),
+                new ProvidedInterfaceNode(_internal, _internal
+                        .getProvidedInterfaces().get(0)));
+    }
+
+    public void testWrongExternal() {
+        EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+                _externalInterfaceName + "x", _internalComponentName,
+                _internalInterfaceName);
+        assertFalse(filter.isViolated(_edge));
+    }
+
+    public void testRightExternalWrongComponent() {
+        EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+                _externalInterfaceName, _internalComponentName + "x",
+                _internalInterfaceName);
+        assertTrue(filter.isViolated(_edge));
+    }
+
+    public void testRightExternalWrongInternal() {
+        EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+                _externalInterfaceName, _internalComponentName,
+                _internalInterfaceName + "x");
+        assertTrue(filter.isViolated(_edge));
+    }
+    
+    public void testEverythingRight() { 
+        EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+                _externalInterfaceName, _internalComponentName,
+                _internalInterfaceName);
+        assertFalse(filter.isViolated(_edge));
+    }
+
+
+    public void testWrongEdgeType() {
+        EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(
+                _externalInterfaceName, _internalComponentName,
+                _internalInterfaceName);
+        DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
+                new DefaultNode("y"));
+        assertFalse(filter.isViolated(edge));
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java
new file mode 100644 (file)
index 0000000..7e8e02c
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import junit.framework.TestCase;
+
+import org.wamblee.system.container.Application;
+import org.wamblee.system.container.Container;
+import org.wamblee.system.core.Component;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.graph.DefaultEdge;
+import org.wamblee.system.graph.DefaultNode;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFilter;
+import org.wamblee.system.graph.Node;
+
+public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase {
+
+    private Component<?> _comp;
+    private Container _container;
+    private Edge _edge;
+
+    @Override
+    protected void setUp() throws Exception {
+        _comp = new Application();
+        _container = new Container("container")
+                .addRequiredInterface(new DefaultRequiredInterface("x",
+                        String.class));
+        Node req = new RequiredInterfaceNode(_comp, _comp
+                .getRequiredInterfaces().get(0));
+        Node external = new ExternalRequiredInterfaceNode(_container,
+                _container.getRequiredInterfaces().get(0));
+        _edge = new DefaultEdge(req, external);
+    }
+
+    public void testRightComponentRightInterface() {
+        EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+                _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(),
+                _container.getRequiredInterfaces().get(0).getName());
+        assertFalse(filter.isViolated(_edge));
+    }
+
+    public void testWrongInterface() {
+        EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+                _comp.getName(), _comp.getRequiredInterfaces().get(0).getName()
+                        + "xx", _container.getRequiredInterfaces().get(0).getName());
+        assertFalse(filter.isViolated(_edge));
+    }
+
+    public void testWrongComponent() {
+        EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+                _comp.getName() + "xx", _comp.getRequiredInterfaces().get(0)
+                        .getName(), _container.getRequiredInterfaces().get(0)
+                        .getName());
+        assertFalse(filter.isViolated(_edge));
+    }
+
+    public void testWrongExternalInterface() {
+        EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+                _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(),
+                _container.getRequiredInterfaces().get(0).getName() + "xx");
+        assertTrue(filter.isViolated(_edge));
+    }
+
+    public void testWrongEdgeType() {
+        DefaultEdge edge = new DefaultEdge(new DefaultNode("x"),
+                new DefaultNode("y"));
+        EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(
+                _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(),
+                _container.getRequiredInterfaces().get(0).getName());
+        assertFalse(filter.isViolated(edge));
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java b/tags/wamblee-utils-0.2.1/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java
new file mode 100644 (file)
index 0000000..0cb9013
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright 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.wamblee.system.graph.component;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.wamblee.system.container.Application;
+import org.wamblee.system.core.Environment;
+import org.wamblee.system.graph.DefaultEdge;
+import org.wamblee.system.graph.Edge;
+import org.wamblee.system.graph.EdgeFilter;
+import org.wamblee.system.graph.Node;
+import org.wamblee.test.AssertionUtils;
+
+import junit.framework.TestCase;
+
+public class ConnectRequiredProvidedEdgeFilterTest extends TestCase {
+
+    private Application _app1 = new Application("app1", "pf1.");
+    private Application _app2 = new Application("app2", "pf2.");
+    
+    private Environment _env1 = new Environment("env1", "pf3.");
+    private Environment _env2 = new Environment("env2", "pf4.");
+    
+    private void compare(Boolean[] aExpected, EdgeFilter aRestriction) { 
+       List<Boolean> result = new ArrayList<Boolean>();
+       
+      
+       
+       // order will be: 
+       //     env1, app1
+       //     env1, app2
+       //     env2, app1
+       //     env2, app2
+       for (Environment env: new Environment[] { _env1, _env2} ) { 
+           for (Application app: new Application[] { _app1, _app2} ) {
+               Node from = new RequiredInterfaceNode(
+                       app, app.getRequiredInterfaces().get(0));
+               Node to = new ProvidedInterfaceNode(
+                       env, env.getProvidedInterfaces().get(0));
+               Edge edge = new DefaultEdge(from, to); 
+               result.add(aRestriction.isViolated(edge));
+           }
+       }
+     
+       
+       assertEquals(Arrays.asList(aExpected), result);
+    }
+
+    public void testNoRestriction() { 
+        AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+            @Override
+            public void run() throws Exception {
+                EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, null, null);
+                
+            }
+        }, IllegalArgumentException.class);
+        AssertionUtils.assertException(new AssertionUtils.ErroneousCode() {
+            @Override
+            public void run() throws Exception {
+                EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, "x", "y");
+            }
+        }, IllegalArgumentException.class);
+    }
+    
+    public void testClientServer() { 
+        EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1", null, "env1", null);
+        compare(new Boolean[] { false, false, true, false}, restriction);
+    }
+    
+    public void testNoConnectionsAtAll() { 
+        EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1", null, null, null);
+        compare(new Boolean[] { true, false, true, false}, restriction);
+    }
+    
+    public void testExplicitConfig() { 
+        _app1 = new Application("app1");
+        _app2 = new Application("app2");
+        _env1 = new Environment("env1");
+        _env2 = new Environment("env2");
+        
+        EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(
+                "app2", "string", "env1", "datasource");
+        compare(new Boolean[] { false, false, false, true}, restriction);
+        
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/pom.xml b/tags/wamblee-utils-0.2.1/system/pom.xml
new file mode 100644 (file)
index 0000000..d9affbe
--- /dev/null
@@ -0,0 +1,20 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-system</artifactId>
+  <packaging>pom</packaging>
+  <name>/system</name>
+  <url>http://wamblee.org</url>
+  <modules>
+    <module>general</module>
+    <module>spring</module>
+  </modules>
+  
+</project>
diff --git a/tags/wamblee-utils-0.2.1/system/spring/pom.xml b/tags/wamblee-utils-0.2.1/system/spring/pom.xml
new file mode 100644 (file)
index 0000000..cca0011
--- /dev/null
@@ -0,0 +1,58 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <parent>
+        <groupId>org.wamblee</groupId>
+        <artifactId>wamblee-utils</artifactId>
+        <version>0.2.1</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-system-spring</artifactId>
+    <packaging>jar</packaging>
+    <version>0.2.1</version>
+    <name>/system/spring</name>
+    <url>http://wamblee.org</url>
+    <dependencies>
+        <dependency>
+            <groupId>org.wamblee</groupId>
+            <artifactId>wamblee-support-general</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wamblee</groupId>
+            <artifactId>wamblee-system-general</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wamblee</groupId>
+            <artifactId>wamblee-support-spring</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.wamblee</groupId>
+            <artifactId>wamblee-support-spring</artifactId>
+            <version>${project.version}</version>
+            <type>test-jar</type>
+        </dependency>
+        <dependency>
+            <groupId>org.wamblee</groupId>
+            <artifactId>wamblee-hibernate-jpa</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-beans</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-context</artifactId>
+        </dependency>
+
+    </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java
new file mode 100644 (file)
index 0000000..7443b57
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+public class ConfiguredProperties extends Properties {
+
+    public ConfiguredProperties(String aProps) throws IOException { 
+        InputStream is = new ByteArrayInputStream(aProps.getBytes()); 
+        load(is); 
+        is.close();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java
new file mode 100644 (file)
index 0000000..f88c405
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.util.Properties;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
+
+/**
+ * Bean that provides postprocessing of the bean factory based on 
+ * a given set of properties. 
+ * 
+ * @author Erik Brakkee
+ */
+class PropertySetter extends PropertyPlaceholderConfigurer {
+
+       /**
+        * Constructs the property setter. 
+        * @param aProps Properties. 
+        */
+       public PropertySetter(Properties aProps) { 
+                String propFile = createPropertyFile(aProps); 
+                setLocation(new StringResource(propFile));
+       }
+
+    public static String createPropertyFile(Properties aProps) {
+        StringBuffer buf = new StringBuffer();  
+                for (Object key: aProps.keySet()) {  
+                        buf.append(key);
+                        buf.append("=");
+                        buf.append(aProps.get(key));
+                        buf.append("\n");
+                }
+        return buf.toString();
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java
new file mode 100644 (file)
index 0000000..71ac308
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.util.List;
+
+import org.springframework.beans.factory.FactoryBean;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.SystemAssemblyException;
+
+/**
+ * Bean which adds a service required by the spring component to 
+ * the application context so that other spring beans can use it.  
+ *  
+ * @author Erik Brakkee
+ */
+class RequiredServiceBean implements FactoryBean {
+       
+       private RequiredInterface _required; 
+       
+       /**
+        * Constructs the bean. 
+        * @param aId Id of the bean in the service registry.  
+        */
+       public RequiredServiceBean(String aId) { 
+               List<RequiredInterface> required = SpringComponent.THIS.get().getRequiredInterfaces();
+               for ( RequiredInterface intf: required) { 
+                       if ( intf.getName().equals(aId)) { 
+                               _required = intf; 
+                               return;
+                       }
+               }
+               throw new SystemAssemblyException("Cannot resolve required component '" + aId + "'");
+       }
+
+       @Override
+       public Object getObject() throws Exception {
+               return SpringComponent.SCOPE.get().getInterfaceImplementation(
+                               _required.getProvider(), Object.class);
+       }
+
+       @Override
+       public Class getObjectType() {
+               return null;
+       }
+
+       @Override
+       public boolean isSingleton() {
+               return true; 
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java
new file mode 100644 (file)
index 0000000..88746a5
--- /dev/null
@@ -0,0 +1,202 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.springframework.beans.MutablePropertyValues;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.beans.factory.config.ConstructorArgumentValues;
+import org.springframework.beans.factory.support.RootBeanDefinition;
+import org.springframework.context.support.AbstractApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+import org.springframework.context.support.GenericApplicationContext;
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultScope;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.SystemAssemblyException;
+
+/**
+ * Represents a system configured based on spring. The spring config files that
+ * are configured should not contain any PropertyPlaceholderConfigurer objects.
+ * 
+ * @author Erik Brakkee
+ */
+public class SpringComponent extends AbstractComponent<Scope> {
+
+       private static final String CONTEXT_KEY = "context";
+
+       static final ThreadLocal<SpringComponent> THIS = new ThreadLocal<SpringComponent>();
+       static final ThreadLocal<Scope> SCOPE = new ThreadLocal<Scope>();
+
+       private Properties _properties;
+       private String[] _configFiles;
+       private Map<String, ProvidedInterface> _provided;
+       private Map<RequiredInterface, String> _required;
+       private Map<String, Properties> _propertyObjects;
+
+       /**
+        * Constructs a spring system.
+        * 
+        * @param aName
+        *            Name of the system.
+        * @param aConfigFil
+        *            Spring config files to read.
+        * @param aProvided
+        *            Map of bean name to service descriptor describing the bean
+        *            names that the spring config files use for each required
+        *            service.
+        * @param aRequired
+        *            Map of bean name to service descriptor describing the bean
+        *            names that the spring config files use for each required
+        *            service.
+        */
+       public SpringComponent(String aName, String[] aConfigFiles,
+                       Map<String, ProvidedInterface> aProvided,
+                       Map<RequiredInterface, String> aRequired) {
+               super(aName, aProvided.values().toArray(new ProvidedInterface[0]),
+                               aRequired.keySet().toArray(new RequiredInterface[0]));
+               _properties = new Properties();
+               _configFiles = aConfigFiles;
+               _provided = aProvided;
+               _required = aRequired;
+               _propertyObjects = new HashMap<String, Properties>(); 
+               
+       }
+
+       /**
+        * Must be called to make a property available in the application context.
+        * 
+        * @param aKey
+        *            Property key.
+        * @param aValue
+        *            Property value.
+        */
+       public void setProperty(String aKey, String aValue) {
+               _properties.put(aKey, aValue);
+       }
+
+       public void addProperties(Properties aProperties) {
+               for (Object key : aProperties.keySet()) {
+                       setProperty((String) key, aProperties.getProperty((String) key));
+               }
+       }
+       
+       public void addProperties(String aBeanname, Properties aProperties) { 
+           _propertyObjects.put(aBeanname, aProperties);
+       }
+       
+       public Properties getProperties(String aBeanname) { 
+           return _propertyObjects.get(aBeanname);
+       }
+
+       @Override
+       protected Scope doStart(Scope aExternalScope) {
+
+               SpringComponent old = THIS.get();
+               Scope oldScope = SCOPE.get();
+               THIS.set(this);
+               Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope);
+               SCOPE.set(scope);
+               try {
+                       GenericApplicationContext parentContext = new GenericApplicationContext();
+
+                       registerRequiredServices(parentContext);
+                       registerPropertyObjects(parentContext);
+
+                       parentContext.refresh();
+                       
+                       System.out.println("Parent context " + parentContext);
+                   
+                       AbstractApplicationContext context = parseConfigFiles(parentContext);
+
+                       context
+                                       .addBeanFactoryPostProcessor(new PropertySetter(_properties));
+                       context.refresh();
+
+                       exposeProvidedServices(context, aExternalScope);
+                       
+                       scope.put(CONTEXT_KEY, context);
+                       return scope; 
+               } catch (Exception e) {
+                       throw new SystemAssemblyException(
+                                       "Failed to assemble spring system " + getName(), e);
+               } finally {
+                       THIS.set(old);
+                       SCOPE.set(oldScope);
+               }
+       }
+
+       private void exposeProvidedServices(AbstractApplicationContext aContext, Scope aScope) {
+               // Call addService for each provided service.
+
+               for (String name : _provided.keySet()) {
+                       Object svc = aContext.getBean(name);
+                       if (svc == null) {
+                               throw new IllegalArgumentException(getQualifiedName() + ": service '"
+                                               + name + "' is null");
+                       }
+                       addInterface(_provided.get(name), svc, aScope);
+                       System.out.println("addService " + _provided.get(name) + " " + svc);
+               }
+       }
+
+       private AbstractApplicationContext parseConfigFiles(GenericApplicationContext aParentContext) {
+               // Parse spring config files
+
+               return new ClassPathXmlApplicationContext((String[]) _configFiles,
+                               false, aParentContext);
+       }
+
+       private void registerRequiredServices(GenericApplicationContext aParentContext) {
+               // Register required services in a parent context
+               for (RequiredInterface required: getRequiredInterfaces()) { 
+                       String beanName = _required.get(required);
+                       if ( beanName != null && beanName.length() > 0) { 
+                           ConstructorArgumentValues cargs = new ConstructorArgumentValues();
+                   cargs.addGenericArgumentValue(required.getName());
+                   BeanDefinition definition = new RootBeanDefinition(
+                           RequiredServiceBean.class, cargs,
+                           new MutablePropertyValues());
+                   aParentContext.registerBeanDefinition(beanName, definition);
+                       } else { 
+                           // The required interface is not required by the spring config but by the sub-class directly.
+                       }
+               }
+       }
+       
+       private void registerPropertyObjects(GenericApplicationContext aParentContext) {
+        for (String beanName: _propertyObjects.keySet()) { 
+            ConstructorArgumentValues cargs = new ConstructorArgumentValues();
+            cargs.addGenericArgumentValue(PropertySetter.createPropertyFile(_propertyObjects.get(beanName)));
+            BeanDefinition definition = new RootBeanDefinition(
+                    ConfiguredProperties.class, cargs,
+                    new MutablePropertyValues());
+            aParentContext.registerBeanDefinition(beanName, definition);
+        }
+    }
+
+
+       @Override
+       protected void doStop(Scope aRuntime) {
+               AbstractApplicationContext context = (AbstractApplicationContext)aRuntime.get(CONTEXT_KEY);
+               context.close();
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java
new file mode 100644 (file)
index 0000000..3f9a791
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+import org.springframework.core.io.Resource;
+
+class StringResource implements Resource {
+       
+       private String _value; 
+       
+       public StringResource(String aValue) { 
+               _value = aValue; 
+       }
+
+       @Override
+       public Resource createRelative(String aRelativePath) throws IOException {
+               throw new IOException("No relative resource possible");
+       }
+
+       @Override
+       public boolean exists() {
+               return false;
+       }
+
+       @Override
+       public String getDescription() {
+               return "Properties of a spring component"; 
+       }
+
+       @Override
+       public File getFile() throws IOException {
+               throw new IOException();
+       }
+
+       @Override
+       public String getFilename() {
+               return "springcomponent.properties";
+       }
+
+       @Override
+       public URL getURL() throws IOException {
+               throw new IOException();
+       }
+
+       @Override
+       public boolean isOpen() {
+               return false;
+       }
+
+       @Override
+       public InputStream getInputStream() throws IOException {
+               return new ByteArrayInputStream(_value.getBytes());
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java
new file mode 100644 (file)
index 0000000..a8d53d4
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright 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.wamblee.system.spring.component;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TreeMap;
+
+import javax.sql.DataSource;
+
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.wamblee.system.components.ORMappingConfig;
+import org.wamblee.system.components.ORMappingConfig.DatabaseType;
+import org.wamblee.system.core.AbstractComponent;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.SpringComponent;
+
+public class DatasourceComponent extends AbstractComponent<DataSource> {
+
+    private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops", Properties.class);
+    private static ProvidedInterface DATASOURCE =  new DefaultProvidedInterface("datasource",
+            DataSource.class);
+    private static ProvidedInterface ORM_CONFIG = new DefaultProvidedInterface("ormconfig",
+            ORMappingConfig.class);
+   
+    public DatasourceComponent(String aName) throws IOException {
+        super(aName); 
+        
+        addRequiredInterface(PROPS);
+        addProvidedInterface(DATASOURCE);
+        addProvidedInterface(ORM_CONFIG);
+    }
+
+
+    @Override
+    protected DataSource doStart(Scope aScope) {
+        Properties dbProps = aScope.getInterfaceImplementation(
+                PROPS.getProvider(), Properties.class);
+        DriverManagerDataSource ds = new DriverManagerDataSource(
+                dbProps.getProperty("database.url"), 
+                dbProps.getProperty("database.username"),
+                dbProps.getProperty("database.password"));
+       addInterface(DATASOURCE, ds, aScope);
+       DatabaseType type = DatabaseType.valueOf(dbProps.getProperty("database.type"));
+       
+       ORMappingConfig config = new ORMappingConfig(true, type);
+       
+       addInterface(ORM_CONFIG, config, aScope);
+       
+       return ds; 
+    }
+
+    @Override
+    protected void doStop(DataSource aRuntime) {
+       // Empty.
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java b/tags/wamblee-utils-0.2.1/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java
new file mode 100644 (file)
index 0000000..4b25625
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+ * Copyright 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.wamblee.system.spring.component;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.dialect.DerbyDialect;
+import org.hibernate.dialect.MySQLInnoDBDialect;
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.wamblee.persistence.hibernate.HibernateMappingFiles;
+import org.wamblee.system.components.ORMappingConfig;
+import org.wamblee.system.components.ORMappingConfig.DatabaseType;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.spring.SpringComponent;
+
+public class HibernateComponent extends SpringComponent {
+
+    private static final String HIBERNATE_DIALECT_PROP = "hibernate.dialect";
+    private static final String HIBERNATE_SCHEMAUPDATE_PROP = "hibernate.schemaupdate";
+    private static final String HIBERNATE_PROPS_KEY = "hibernateProperties";
+    private static final String HIBERNATE_SPRING_CONFIG = "spring/org.wamblee.system.spring.component.hibernate.xml";
+    
+    private final RequiredInterface CONFIG = new DefaultRequiredInterface("config", ORMappingConfig.class);
+
+    public HibernateComponent(String aName) throws IOException { 
+        super(aName, new String[] { HIBERNATE_SPRING_CONFIG}, 
+                createProvided(), createRequired()); 
+        
+        Properties props = new Properties(); 
+        addProperties(HIBERNATE_PROPS_KEY, props);
+   
+        addRequiredInterface(CONFIG);
+    }
+    
+    @Override
+    protected Scope doStart(Scope aExternalScope) {
+        
+        ORMappingConfig config = aExternalScope.getInterfaceImplementation(CONFIG.getProvider(), ORMappingConfig.class);
+        setProperty(HIBERNATE_SCHEMAUPDATE_PROP, "" + config.isSchemaUpdate());
+        
+        DatabaseType db = config.getType(); 
+        String dialect = db.handleCases(new DatabaseType.Switch<String>() { 
+            @Override
+            public String handleMySqlInnoDb() {
+                return MySQLInnoDBDialect.class.getName(); 
+            }
+            @Override
+            public String handleDerby() {
+                return DerbyDialect.class.getName(); 
+            }
+        });
+        getHibernateProperties().put(HIBERNATE_DIALECT_PROP, dialect);
+        
+        
+        return super.doStart(aExternalScope);
+    }
+    
+    private Properties getHibernateProperties() { 
+        return getProperties(HIBERNATE_PROPS_KEY);
+    }
+
+    private static Map<RequiredInterface, String> createRequired() {
+        Map<RequiredInterface,String> required = new HashMap<RequiredInterface, String>();
+        required.put(new DefaultRequiredInterface("datasource", DataSource.class), "dataSource");
+        required.put(new DefaultRequiredInterface("mappingFiles", HibernateMappingFiles.class), 
+                "hibernateMappingFiles");
+        return required;
+    }
+
+    private static Map<String, ProvidedInterface> createProvided() {
+        Map<String,ProvidedInterface> provided = new HashMap<String,ProvidedInterface>(); 
+        
+        provided.put("transactionManager", new DefaultProvidedInterface(
+                "transactionMgr", PlatformTransactionManager.class));
+        provided.put("sessionFactory", new DefaultProvidedInterface(
+                "sessionFactory", SessionFactory.class));
+        provided.put("org.springframework.orm.hibernate3.HibernateTemplate", new DefaultProvidedInterface(
+                "hibernateTemplate", HibernateTemplate.class));
+        return provided;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/resources/properties/org.wamblee.system.spring.component.hibernate.properties b/tags/wamblee-utils-0.2.1/system/spring/src/main/resources/properties/org.wamblee.system.spring.component.hibernate.properties
new file mode 100644 (file)
index 0000000..5c38ff6
--- /dev/null
@@ -0,0 +1,15 @@
+
+###################################################################################
+# dialect
+###################################################################################
+#hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
+
+###################################################################################
+# hibernate cache provider
+###################################################################################
+#hibernate.cache.provider=org.hibernate.cache.EhCacheProvider
+
+###################################################################################
+# query cache
+###################################################################################
+#hibernate.cache.use_query_cache=true
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/main/resources/spring/org.wamblee.system.spring.component.hibernate.xml b/tags/wamblee-utils-0.2.1/system/spring/src/main/resources/spring/org.wamblee.system.spring.component.hibernate.xml
new file mode 100644 (file)
index 0000000..73c02b4
--- /dev/null
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
+
+<!-- This is the Spring configuration to define the database-related stuff for the
+    all persistence tests.  -->
+<beans>
+    
+    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
+        <property name="dataSource">
+            <ref bean="dataSource"/>
+        </property>
+        <property name="hibernateProperties">
+            <ref bean="hibernateProperties"/>
+        </property>
+        <property name="schemaUpdate">
+            <value>${hibernate.schemaupdate}</value>
+        </property>
+        <property name="mappingResources"><ref bean="hibernateMappingFiles"/></property>
+    </bean>
+    
+    <bean id="transactionManager"
+        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
+        <property name="sessionFactory">
+            <ref local="sessionFactory"/>
+        </property>
+    </bean>
+    
+    <!--  Hibernate template used within test code for addition 
+            Hibernate-specific stuff -->
+    <bean id="org.springframework.orm.hibernate3.HibernateTemplate" 
+        class="org.springframework.orm.hibernate3.HibernateTemplate">
+        <property name="sessionFactory">
+            <ref bean="sessionFactory"/>
+        </property>
+    </bean>
+</beans>
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java
new file mode 100644 (file)
index 0000000..5bbafa1
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+public class BlaService {
+       private HelloService _hello; 
+       
+       public BlaService(HelloService aService) {
+               if ( aService == null ) { 
+                       throw new IllegalArgumentException("helloService is null"); 
+               }
+               _hello = aService; 
+       }
+       
+       public String execute() { 
+               return _hello.say(); 
+       }
+       
+       public void stop() { 
+               System.out.println("Blaservice stopping");
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java
new file mode 100644 (file)
index 0000000..00002de
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.io.IOException;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+public class ConfiguredPropertiesTest extends TestCase {
+
+    public void testProps() throws IOException { 
+        Properties props = new Properties();
+        props.put("x", "y");
+        props.put("a", "b"); 
+        
+        ConfiguredProperties props2 = new ConfiguredProperties(
+                PropertySetter.createPropertyFile(props)); 
+        
+        assertEquals(props.size(), props2.size()); 
+        assertEquals(props.get("x"), props2.get("x"));
+        assertEquals(props.get("a"), props2.get("a"));
+    }
+}
+
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java
new file mode 100644 (file)
index 0000000..cfa5bae
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+public class HelloService {
+       
+       private String _msg; 
+       
+       public HelloService(String aMsg) {
+          SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg);
+               _msg = aMsg; 
+       }
+       
+       public String say() { 
+               return _msg; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java
new file mode 100644 (file)
index 0000000..e9c7708
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.util.Properties;
+
+public class HelloService2 {
+
+    private Properties _props;
+
+    public HelloService2(Properties aProps) {
+        _props = aProps;
+    }
+
+    public Properties getProperties() { 
+        return _props; 
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java
new file mode 100644 (file)
index 0000000..1cc95c1
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.wamblee.io.ClassPathResource;
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.DefaultScope;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+import org.wamblee.system.core.SystemAssemblyException;
+import org.wamblee.test.EventTracker;
+
+public class SpringComponentTest extends TestCase {
+
+    private static final String HELLO_SERVICE_SPRING_XML = "test.org.wamblee.system.spring.xml";
+    private static final String HELLO_SERVICE_SPRING_WITH_REQS_XML = "test.org.wamblee.system.springWithRequirements.xml";
+    private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML = "test.org.wamblee.system.springWithProperties.xml";
+    private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 = "test.org.wamblee.system.springWithProperties2.xml";
+
+    private static final String PROPERTY_FILE = "test.org.wamblee.system.spring.properties";
+
+    public static EventTracker<String> EVENT_TRACKER;
+
+    private Scope _externalScope;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        EVENT_TRACKER = new EventTracker<String>();
+        _externalScope = new DefaultScope(new ProvidedInterface[0]);
+    }
+
+    public void testBlackboxSystem() {
+        SpringComponent system = new SpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_XML },
+                new HashMap<String, ProvidedInterface>(),
+                new HashMap<RequiredInterface, String>());
+
+        Scope runtime = system.start(_externalScope);
+        assertEquals(0, _externalScope.getProvidedInterfaces().size()); 
+
+        system.stop(runtime);
+    }
+
+    public void testOneProvidedService() {
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put("helloService", new DefaultProvidedInterface("hello",
+                HelloService.class));
+
+        SpringComponent system = new SpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_XML }, provided,
+                new HashMap<RequiredInterface, String>());
+        Scope runtime = system.start(_externalScope);
+        List<ProvidedInterface> services = runtime.getProvidedInterfaces();
+
+        assertEquals(1, services.size());
+        Object service = runtime.getInterfaceImplementation(services.get(0),
+                Object.class);
+        assertTrue(service instanceof HelloService);
+
+        // BUG; Provided services should be made available in the external
+        // scope.
+        Object service2 = _externalScope.getInterfaceImplementation(provided
+                .get("helloService"), Object.class);
+        assertSame(service, service2);
+
+        assertEquals("Hello world!", ((HelloService) service).say());
+        system.stop(runtime);
+    }
+
+    public void testWithProperties() throws IOException {
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put("helloService", new DefaultProvidedInterface("hello",
+                HelloService.class));
+        SpringComponent system = new SpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML },
+                provided, new HashMap<RequiredInterface, String>());
+        Properties props = new Properties();
+        props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
+        system.addProperties(props);
+
+        Scope scope = system.start(_externalScope);
+        // BUG: Hello service was constructed multiple times. Once with the
+        // unprocessed property
+        // and another time with the processed property.
+        assertEquals(1, EVENT_TRACKER.getEventCount());
+        List<ProvidedInterface> services = scope.getProvidedInterfaces();
+        assertEquals("Property Value", scope.getInterfaceImplementation(
+                services.get(0), HelloService.class).say());
+    }
+
+    public void testWithPropertiesAsBean() throws IOException {
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put("helloService", new DefaultProvidedInterface("hello",
+                HelloService2.class));
+        SpringComponent system = new SpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 },
+                provided, new HashMap<RequiredInterface, String>());
+        Properties props = new Properties();
+        props.load(new ClassPathResource(PROPERTY_FILE).getInputStream());
+        system.addProperties("properties", props);
+
+        Scope scope = system.start(_externalScope);
+
+        List<ProvidedInterface> services = scope.getProvidedInterfaces();
+
+        Properties props2 = scope.getInterfaceImplementation(services.get(0),
+                HelloService2.class).getProperties();
+        assertEquals(props, props2);
+    }
+
+    public void testWithMissingRequirement() {
+        try {
+            SpringComponent system = new SpringComponent("system",
+                    new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
+                    new HashMap<String, ProvidedInterface>(),
+                    new HashMap<RequiredInterface, String>());
+            system.start(_externalScope);
+        } catch (SystemAssemblyException e) {
+            // e.printStackTrace();
+            return;
+        }
+        fail();
+    }
+
+    public void testWithRequirement() {
+        Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+        required.put(new DefaultRequiredInterface("hello", HelloService.class),
+                "helloService");
+        SpringComponent system = new SpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
+                new HashMap<String, ProvidedInterface>(), required);
+
+        HelloService helloObject = new HelloService("ladida");
+        ProvidedInterface helloService = new DefaultProvidedInterface("hello",
+                HelloService.class);
+        Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
+        scope.publishInterface(helloService, helloObject);
+        system.getRequiredInterfaces().get(0).setProvider(helloService);
+
+        Scope runtime = system.start(scope);
+        system.stop(runtime);
+    }
+
+    public void testWithRequirementAndProvidedService() {
+        Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+        required.put(new DefaultRequiredInterface("hello", HelloService.class),
+                "helloService");
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put("blaService", new DefaultProvidedInterface("bla",
+                BlaService.class));
+
+        SpringComponent system = new SpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, provided,
+                required);
+
+        HelloService helloObject = new HelloService("ladida");
+        ProvidedInterface helloService = new DefaultProvidedInterface("hello",
+                HelloService.class);
+        Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
+        scope.publishInterface(helloService, helloObject);
+        system.getRequiredInterfaces().get(0).setProvider(helloService);
+        Scope runtime = system.start(scope);
+        ProvidedInterface started = runtime.getProvidedInterfaces().get(0);
+
+        Object impl = runtime.getInterfaceImplementation(started,
+                BlaService.class);
+        assertNotNull(impl);
+        assertTrue(impl instanceof BlaService);
+        assertEquals("ladida", ((BlaService) impl).execute());
+        system.stop(runtime);
+    }
+
+    /**
+     * Tests a scenario where a subclass of SpringComponent adds a new provided
+     * interface where the interface is provided by the subclass itself and not
+     * by the spring configs inside.
+     */
+    public void testWithProvidedFromSubClassNotFromConfig() {
+        Map<String, ProvidedInterface> provided = new HashMap<String, ProvidedInterface>();
+        provided.put("helloService", new DefaultProvidedInterface("hello",
+                HelloService.class));
+
+        SubSpringComponent system = new SubSpringComponent("system",
+                new String[] { HELLO_SERVICE_SPRING_XML }, provided,
+                new HashMap<RequiredInterface, String>());
+
+        Scope runtime = system.start(_externalScope);
+        List<ProvidedInterface> services = runtime.getProvidedInterfaces();
+
+        assertEquals(2, services.size());
+        Object service = runtime.getInterfaceImplementation(services.get(0),
+                Object.class);
+        assertTrue(service instanceof HelloService);
+
+        // BUG; Provided services should be made available in the external
+        // scope.
+        Object service2 = _externalScope.getInterfaceImplementation(provided
+                .get("helloService"), Object.class);
+        assertSame(service, service2);
+
+        Object floatsvc = _externalScope.getInterfaceImplementation(system
+                .getProvidedInterfaces().get(1), Object.class);
+        assertTrue(floatsvc instanceof Float);
+        assertTrue((((Float) floatsvc).floatValue() - 100.345f) < 0.00001);
+
+        assertEquals("Hello world!", ((HelloService) service).say());
+        system.stop(runtime);
+    }
+
+    /**
+     * Tests the spring component with an additional requirement from the subclass 
+     * which is not required by the spring config files inside. 
+     */
+    public void testWithRequirementFromSubClass() {
+        Map<RequiredInterface, String> required = new HashMap<RequiredInterface, String>();
+        required.put(new DefaultRequiredInterface("hello", HelloService.class),
+                "helloService");
+        SpringComponent system = new SubSpringComponent2("system",
+                new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML },
+                new HashMap<String, ProvidedInterface>(), required);
+
+        HelloService helloObject = new HelloService("ladida");
+        ProvidedInterface helloService = new DefaultProvidedInterface("hello",
+                HelloService.class);
+        
+        ProvidedInterface floatService = new DefaultProvidedInterface("float", Float.class);
+        
+        Scope scope = new DefaultScope(new ProvidedInterface[] { helloService });
+        scope.publishInterface(helloService, helloObject);
+        scope.publishInterface(floatService, 100.234f);
+        system.getRequiredInterfaces().get(0).setProvider(helloService);
+        system.getRequiredInterfaces().get(1).setProvider(floatService);
+
+        Scope runtime = system.start(scope);
+        system.stop(runtime);
+        
+        assertEquals(100.234f, ((Float)runtime.get("floatValue")).floatValue(), 0.0001f);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java
new file mode 100644 (file)
index 0000000..5e79a7a
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.util.Map;
+
+
+import org.wamblee.system.core.DefaultProvidedInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+public class SubSpringComponent extends SpringComponent {
+    
+    private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided", Float.class); 
+
+    public SubSpringComponent(String aName, String[] aConfigFiles,
+            Map<String, ProvidedInterface> aProvided,
+            Map<RequiredInterface, String> aRequired) { 
+        super(aName, aConfigFiles, aProvided, aRequired);
+        addProvidedInterface(PROVIDED);
+    }
+    
+    @Override
+    protected Scope doStart(Scope aExternalScope) {
+        
+        Scope scope = super.doStart(aExternalScope);
+        addInterface(PROVIDED, 100.345f, aExternalScope);
+        return scope;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java
new file mode 100644 (file)
index 0000000..7b67cc4
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright 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.wamblee.system.spring;
+
+import java.util.Map;
+
+import org.wamblee.system.core.DefaultRequiredInterface;
+import org.wamblee.system.core.ProvidedInterface;
+import org.wamblee.system.core.RequiredInterface;
+import org.wamblee.system.core.Scope;
+
+public class SubSpringComponent2 extends SpringComponent {
+    
+    private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required", Float.class); 
+
+    public SubSpringComponent2(String aName, String[] aConfigFiles,
+            Map<String, ProvidedInterface> aProvided,
+            Map<RequiredInterface, String> aRequired) { 
+        super(aName, aConfigFiles, aProvided, aRequired);
+        addRequiredInterface(REQUIRED);
+    }
+    
+    @Override
+    protected Scope doStart(Scope aExternalScope) {
+        
+        Scope scope = super.doStart(aExternalScope);
+     
+        float value = aExternalScope.getInterfaceImplementation(REQUIRED.getProvider(), Float.class);
+        scope.put("floatValue", value);
+        return scope;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java b/tags/wamblee-utils-0.2.1/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java
new file mode 100644 (file)
index 0000000..b988107
--- /dev/null
@@ -0,0 +1,521 @@
+/*
+ * Copyright 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.wamblee.system.spring.component;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import javax.sql.DataSource;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.dbunit.DatabaseUnitException;
+import org.dbunit.database.DatabaseConnection;
+import org.dbunit.database.DatabaseSequenceFilter;
+import org.dbunit.database.IDatabaseConnection;
+import org.dbunit.dataset.FilteredDataSet;
+import org.dbunit.dataset.IDataSet;
+import org.dbunit.dataset.filter.ITableFilter;
+import org.dbunit.operation.DatabaseOperation;
+import org.hibernate.SessionFactory;
+import org.springframework.beans.factory.NoSuchBeanDefinitionException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceUtils;
+import org.springframework.orm.hibernate3.HibernateTemplate;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.DefaultTransactionDefinition;
+import org.springframework.transaction.support.TransactionCallback;
+import org.springframework.transaction.support.TransactionCallbackWithoutResult;
+import org.springframework.transaction.support.TransactionTemplate;
+import org.wamblee.test.spring.TestTransactionCallback;
+import org.wamblee.test.spring.TestTransactionCallbackWithoutResult;
+
+/**
+ * Test support class for database testing. Currently, this still requires the
+ * spring platform transaction manager and hibernate template.
+ */
+public class DatabaseTesterComponent {
+
+    private static final Log LOG = LogFactory
+            .getLog(DatabaseTesterComponent.class);
+
+    /**
+     * Schema pattern.
+     */
+    private static final String SCHEMA_PATTERN = "%";
+
+    /**
+     * Cached spring application context.
+     */
+    private ApplicationContext _context;
+
+    private HibernateTemplate _hibernateTemplate;
+
+    private PlatformTransactionManager _transactionManager;
+
+    private DataSource _dataSource;
+
+    public DatabaseTesterComponent(HibernateTemplate aHibernateTemplate,
+            PlatformTransactionManager aTransactionManager,
+            DataSource aDataSource) {
+        _hibernateTemplate = aHibernateTemplate;
+        _transactionManager = aTransactionManager;
+        _dataSource = aDataSource;
+    }
+
+    /**
+     * @return Hibernate session factory.
+     */
+    protected SessionFactory getSessionFactory() {
+        return _hibernateTemplate.getSessionFactory();
+    }
+
+    /**
+     * Performs common initialization for test cases:
+     * <ul>
+     * <li>Cleaning the database. </li>
+     * </ul>
+     * 
+     * @throws Exception
+     */
+    public void setUp() throws Exception {
+        LOG.info("Performing setUp()");
+
+        cleanDatabase();
+    }
+
+    /**
+     * Performs common tear down after execution of a test case. Currenlty this
+     * method does nothing.
+     * 
+     * @throws Exception
+     */
+    protected void tearDown() throws Exception {
+        // Empty
+    }
+
+    /**
+     * @return Transaction manager
+     */
+    protected PlatformTransactionManager getTransactionManager() {
+        return _transactionManager;
+    }
+
+    /**
+     * @return Starts a new transaction.
+     */
+    protected TransactionStatus getTransaction() {
+        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
+        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
+
+        return getTransactionManager().getTransaction(def);
+    }
+
+    /**
+     * Returns the hibernate template for executing hibernate-specific
+     * functionality.
+     * 
+     * @return Hibernate template.
+     */
+    public HibernateTemplate getTemplate() {
+        return _hibernateTemplate;
+    }
+
+    /**
+     * Flushes the session. Should be called after some Hibernate work and
+     * before JDBC is used to check results.
+     * 
+     */
+    public void flush() {
+        getTemplate().flush();
+    }
+
+    /**
+     * Flushes the session first and then removes all objects from the Session
+     * cache. Should be called after some Hibernate work and before JDBC is used
+     * to check results.
+     * 
+     */
+    public void clear() {
+        flush();
+        getTemplate().clear();
+    }
+
+    /**
+     * Evicts the object from the session. This is essential for the
+     * implementation of unit tests where first an object is saved and is
+     * retrieved later. By removing the object from the session, Hibernate must
+     * retrieve the object again from the database.
+     * 
+     * @param aObject
+     */
+    protected void evict(Object aObject) {
+        getTemplate().evict(aObject);
+    }
+
+    /**
+     * Gets the connection.
+     * 
+     * @return Connection.
+     */
+    public Connection getConnection() {
+        return DataSourceUtils.getConnection(getDataSource());
+    }
+
+    public void cleanDatabase() throws SQLException {
+
+        if (!isDatabaseConfigured()) {
+            return;
+        }
+
+        String[] tables = getTableNames();
+
+        try {
+            IDatabaseConnection connection = new DatabaseConnection(
+                    getConnection());
+            ITableFilter filter = new DatabaseSequenceFilter(connection, tables);
+            IDataSet dataset = new FilteredDataSet(filter, connection
+                    .createDataSet(tables));
+
+            DatabaseOperation.DELETE_ALL.execute(connection, dataset);
+        } catch (DatabaseUnitException e) {
+            SQLException exc = new SQLException(e.getMessage());
+            exc.initCause(e);
+            throw exc;
+        }
+    }
+
+    /**
+     * @throws SQLException
+     */
+    public String[] getTableNames() throws SQLException {
+
+        List<String> result = new ArrayList<String>();
+        LOG.debug("Getting database table names to clean (schema: '"
+                + SCHEMA_PATTERN + "'");
+
+        ResultSet tables = getConnection().getMetaData().getTables(null,
+                SCHEMA_PATTERN, "%", new String[] { "TABLE" });
+        while (tables.next()) {
+            String table = tables.getString("TABLE_NAME");
+            // Make sure we do not touch hibernate's specific
+            // infrastructure tables.
+            if (!table.toLowerCase().startsWith("hibernate")) {
+                result.add(table);
+                LOG.debug("Adding " + table
+                        + " to list of tables to be cleaned.");
+            }
+        }
+        return (String[]) result.toArray(new String[0]);
+    }
+
+    /**
+     * @return
+     * @throws SQLException
+     */
+    public void emptyTables(List aTableList) throws SQLException {
+        Iterator liTable = aTableList.iterator();
+        while (liTable.hasNext()) {
+            emptyTable((String) liTable.next());
+        }
+    }
+
+    /**
+     * @return
+     * @throws SQLException
+     */
+    public void emptyTable(String aTable) throws SQLException {
+        executeSql("delete from " + aTable);
+    }
+
+    /**
+     * @return
+     * @throws SQLException
+     */
+    public void dropTable(String aTable) throws SQLException {
+        executeQuery("drop table " + aTable);
+    }
+
+    /**
+     * Executes an SQL statement within a transaction.
+     * 
+     * @param aSql
+     *            SQL statement.
+     * @return Return code of the corresponding JDBC call.
+     */
+    public int executeSql(final String aSql) {
+        return executeSql(aSql, new Object[0]);
+    }
+
+    /**
+     * Executes an SQL statement within a transaction. See
+     * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+     * supported argument types.
+     * 
+     * @param aSql
+     *            SQL statement.
+     * @param aArg
+     *            Argument of the sql statement.
+     * @return Return code of the corresponding JDBC call.
+     */
+    public int executeSql(final String aSql, final Object aArg) {
+        return executeSql(aSql, new Object[] { aArg });
+    }
+
+    /**
+     * Executes an sql statement. See
+     * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+     * supported argument types.
+     * 
+     * @param aSql
+     *            SQL query to execute.
+     * @param aArgs
+     *            Arguments.
+     * @return Number of rows updated.
+     */
+    public int executeSql(final String aSql, final Object[] aArgs) {
+        Map results = executeTransaction(new TestTransactionCallback() {
+            public Map execute() throws Exception {
+                JdbcTemplate template = new JdbcTemplate(getDataSource());
+                int result = template.update(aSql, aArgs);
+
+                Map<String, Integer> map = new TreeMap<String, Integer>();
+                map.put("result", new Integer(result));
+
+                return map;
+            }
+        });
+
+        return ((Integer) results.get("result")).intValue();
+    }
+
+    /**
+     * Executes a transaction with a result.
+     * 
+     * @param aCallback
+     *            Callback to do your transactional work.
+     * @return Result.
+     */
+    public Object executeTransaction(TransactionCallback aCallback) {
+        TransactionTemplate lTemplate = new TransactionTemplate(
+                getTransactionManager());
+        return lTemplate.execute(aCallback);
+    }
+
+    /**
+     * Executes a transaction without a result.
+     * 
+     * @param aCallback
+     *            Callback to do your transactional work. .
+     */
+    public void executeTransaction(TransactionCallbackWithoutResult aCallback) {
+        TransactionTemplate template = new TransactionTemplate(
+                getTransactionManager());
+        template.execute(aCallback);
+    }
+
+    /**
+     * Executes a transaction with a result, causing the testcase to fail if any
+     * type of exception is thrown.
+     * 
+     * @param aCallback
+     *            Code to be executed within the transaction.
+     * @return Result.
+     */
+    public Map executeTransaction(final TestTransactionCallback aCallback) {
+        return (Map) executeTransaction(new TransactionCallback() {
+            public Object doInTransaction(TransactionStatus aArg) {
+                try {
+                    return aCallback.execute();
+                } catch (Exception e) {
+                    // test case must fail.
+                    e.printStackTrace();
+                    throw new RuntimeException(e);
+                }
+            }
+        });
+    }
+
+    /**
+     * Executes a transaction with a result, causing the testcase to fail if any
+     * type of exception is thrown.
+     * 
+     * @param aCallback
+     *            Code to be executed within the transaction.
+     */
+    public void executeTransaction(
+            final TestTransactionCallbackWithoutResult aCallback) {
+        executeTransaction(new TransactionCallbackWithoutResult() {
+            public void doInTransactionWithoutResult(TransactionStatus aArg) {
+                try {
+                    aCallback.execute();
+                } catch (Exception e) {
+                    // test case must fail.
+                    throw new RuntimeException(e.getMessage(), e);
+                }
+            }
+        });
+    }
+
+    /**
+     * Executes an SQL query.
+     * 
+     * @param aSql
+     *            Query to execute.
+     * @return Result set.
+     */
+    public ResultSet executeQuery(String aSql) {
+        return executeQuery(aSql, new Object[0]);
+    }
+
+    /**
+     * Executes a query with a single argument. See
+     * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+     * supported argument types.
+     * 
+     * @param aSql
+     *            Query.
+     * @param aArg
+     *            Argument.
+     * @return Result set.
+     */
+    public ResultSet executeQuery(String aSql, Object aArg) {
+        return executeQuery(aSql, new Object[] { aArg });
+    }
+
+    /**
+     * Executes a query. See
+     * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+     * supported argument types.
+     * 
+     * @param aSql
+     *            Sql query.
+     * @param aArgs
+     *            Arguments to the query.
+     * @return Result set.
+     */
+    public ResultSet executeQuery(final String aSql, final Object[] aArgs) {
+        try {
+            Connection connection = getConnection();
+
+            PreparedStatement statement = connection.prepareStatement(aSql);
+            setPreparedParams(aArgs, statement);
+
+            return statement.executeQuery();
+        } catch (SQLException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Sets the values of a prepared statement. See
+     * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+     * supported argument types.
+     * 
+     * @param aArgs
+     *            Arguments to the prepared statement.
+     * @param aStatement
+     *            Prepared statement
+     * @throws SQLException
+     */
+    private void setPreparedParams(final Object[] aArgs,
+            PreparedStatement aStatement) throws SQLException {
+        for (int i = 1; i <= aArgs.length; i++) {
+            setPreparedParam(i, aStatement, aArgs[i - 1]);
+        }
+    }
+
+    /**
+     * Sets a prepared statement parameter.
+     * 
+     * @param aIndex
+     *            Index of the parameter.
+     * @param aStatement
+     *            Prepared statement.
+     * @param aObject
+     *            Value Must be of type Integer, Long, or String. 
+     * @throws SQLException
+     */
+    private void setPreparedParam(int aIndex, PreparedStatement aStatement,
+            Object aObject) throws SQLException {
+        if (aObject instanceof Integer) {
+            aStatement.setInt(aIndex, ((Integer) aObject).intValue());
+        } else if (aObject instanceof Long) {
+            aStatement.setLong(aIndex, ((Integer) aObject).longValue());
+        } else if (aObject instanceof String) {
+            aStatement.setString(aIndex, (String) aObject);
+        } else {
+            TestCase.fail("Unsupported object type for prepared statement: "
+                    + aObject.getClass() + " value: " + aObject
+                    + " statement: " + aStatement);
+        }
+    }
+
+    private boolean isDatabaseConfigured() {
+        try {
+            getDataSource();
+        } catch (NoSuchBeanDefinitionException e) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * @return Returns the dataSource.
+     */
+    public DataSource getDataSource() {
+        return _dataSource;
+    }
+
+    /**
+     * @return
+     * @throws SQLException
+     */
+    public int getTableSize(final String aTable) throws SQLException {
+
+        ResultSet resultSet = executeQuery("select * from " + aTable);
+        int count = 0;
+
+        while (resultSet.next()) {
+            count++;
+        }
+        return count;
+    }
+
+    public int countResultSet(ResultSet aResultSet) throws SQLException {
+        int count = 0;
+
+        while (aResultSet.next()) {
+            count++;
+        }
+
+        return count;
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.spring.properties b/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.spring.properties
new file mode 100644 (file)
index 0000000..747a033
--- /dev/null
@@ -0,0 +1 @@
+myproperty=Property Value
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.spring.xml b/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.spring.xml
new file mode 100644 (file)
index 0000000..238054b
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
+
+    <bean id="helloService" class="org.wamblee.system.spring.HelloService">
+        <constructor-arg>
+            <value>Hello world!</value>
+        </constructor-arg>
+    </bean>
+
+</beans>
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties.xml b/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties.xml
new file mode 100644 (file)
index 0000000..1ece7d1
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
+
+    <bean id="helloService" class="org.wamblee.system.spring.HelloService">
+        <constructor-arg>
+            <value>${myproperty}</value>
+        </constructor-arg>
+    </bean>
+
+</beans>
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties2.xml b/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties2.xml
new file mode 100644 (file)
index 0000000..1546261
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
+
+    <bean id="helloService" class="org.wamblee.system.spring.HelloService2">
+        <constructor-arg>
+            <ref bean="properties"/>
+        </constructor-arg>
+    </bean>
+
+</beans>
diff --git a/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithRequirements.xml b/tags/wamblee-utils-0.2.1/system/spring/src/test/resources/test.org.wamblee.system.springWithRequirements.xml
new file mode 100644 (file)
index 0000000..a2f60d8
--- /dev/null
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
+
+    <bean id="blaService" class="org.wamblee.system.spring.BlaService" destroy-method="stop">
+        <constructor-arg>
+            <ref bean="helloService"/>
+        </constructor-arg>
+    </bean>
+
+</beans>
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/pom.xml b/tags/wamblee-utils-0.2.1/test/eclipselink/pom.xml
new file mode 100644 (file)
index 0000000..b036889
--- /dev/null
@@ -0,0 +1,56 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-test-eclipselink</artifactId>
+  <packaging>jar</packaging>
+  <name>/test/eclipselink</name>
+  <url>http://wamblee.org</url>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+      <type>test-jar</type>
+    </dependency>
+
+    <dependency>
+      <groupId>org.dbunit</groupId>
+      <artifactId>dbunit</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>javax.persistence</groupId>
+      <artifactId>persistence-api</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.eclipse.persistence</groupId>
+      <artifactId>eclipselink</artifactId>
+    </dependency>
+
+  </dependencies>
+
+   <repositories>
+        <repository>
+            <id>EclipseLink Repo</id>
+            <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url>
+        </repository>
+
+    </repositories>
+
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java b/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java
new file mode 100644 (file)
index 0000000..856b051
--- /dev/null
@@ -0,0 +1,30 @@
+package org.wamblee.support.persistence.eclipselink;
+
+import java.util.Map;
+
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.wamblee.support.persistence.JpaCustomizer;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+public class EclipselinkJpaCustomizer implements JpaCustomizer {
+
+    public EclipselinkJpaCustomizer() { 
+        // Empty
+    }
+    
+    @Override
+    public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+        // Hack to make JNDI lookup of the datasource work with toplink
+        aJpaProperties.put("eclipselink.session.customizer", JndiSessionCustomizer.class
+                .getName());
+        
+        // DDL generation for toplink
+        aJpaProperties.put("eclipselink.ddl-generation", "create-tables");   
+    }
+    
+    @Override
+    public ITableFilterSimple getJpaTables() {
+        return new EclipselinkTables();
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java b/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java
new file mode 100644 (file)
index 0000000..d4df0dd
--- /dev/null
@@ -0,0 +1,20 @@
+package org.wamblee.support.persistence.eclipselink;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+/**
+ * Toplink-specific tables. 
+ */
+public class EclipselinkTables implements ITableFilterSimple {
+
+       private static final List<String> TABLES = Arrays.asList(new String[] { "SEQUENCE" } );
+       
+       public boolean accept(String aTableName) throws DataSetException {
+               return TABLES.contains(aTableName);
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java b/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java
new file mode 100644 (file)
index 0000000..9b856f0
--- /dev/null
@@ -0,0 +1,59 @@
+package org.wamblee.support.persistence.eclipselink;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+
+import org.eclipse.persistence.config.SessionCustomizer;
+import org.eclipse.persistence.sessions.DatabaseLogin;
+import org.eclipse.persistence.sessions.JNDIConnector;
+import org.eclipse.persistence.sessions.Session;
+import org.eclipse.persistence.sessions.server.ServerSession;
+/**
+ * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a
+ * JTA SE pu instead of a RESOURCE_LOCAL SE pu.
+ * 
+ * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE 
+ * environment together with our JNDI stub. 
+ */
+public class JndiSessionCustomizer
+    implements SessionCustomizer {
+       
+       public JndiSessionCustomizer() {
+               // Empty.
+       }
+  /**
+   * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP
+   */
+  public void customize(Session session) throws Exception {
+    JNDIConnector connector = null;
+    Context context = null;
+    try {
+      context = new InitialContext();
+      if(null != context) {
+        connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE
+        // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
+        // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
+        // the COMPOSITE_NAME_LOOKUP being set
+        // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
+        connector.setLookupType(JNDIConnector.STRING_LOOKUP);
+        // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
+        JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector();
+        writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+        JNDIConnector readConnector =
+            (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector();
+        readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+        System.out.println("JndiSessionCustomizer: configured " + connector.getName());
+      }
+      else {
+        throw new Exception("JndiSessionCustomizer: Context is null");
+      }
+    }
+    catch(Exception e) {
+      e.printStackTrace();
+    }
+  }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer b/tags/wamblee-utils-0.2.1/test/eclipselink/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer
new file mode 100644 (file)
index 0000000..35638de
--- /dev/null
@@ -0,0 +1 @@
+org.wamblee.support.persistence.eclipselink.EclipselinkJpaCustomizer
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java b/tags/wamblee-utils-0.2.1/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java
new file mode 100644 (file)
index 0000000..870e20a
--- /dev/null
@@ -0,0 +1,23 @@
+package org.wamblee.support.persistence.eclipselink;
+
+import static junit.framework.Assert.assertEquals;
+
+import javax.persistence.EntityManager;
+import javax.sql.DataSource;
+
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.DatabaseUtilsTestBase;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+public class DatabaseUtilsTest extends DatabaseUtilsTestBase {
+   // Empty, all tests inherited
+}
diff --git a/tags/wamblee-utils-0.2.1/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java b/tags/wamblee-utils-0.2.1/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java
new file mode 100644 (file)
index 0000000..84c3fff
--- /dev/null
@@ -0,0 +1,29 @@
+package org.wamblee.support.persistence.eclipselink;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import javax.sql.DataSource;
+
+import org.dbunit.DataSourceDatabaseTester;
+import org.dbunit.DatabaseTestCase;
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaTester;
+import org.wamblee.support.persistence.MyEntityExampleTestBase;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+import static junit.framework.Assert.*;
+
+
+/**
+ * This class shows an example of how to test an entity  using jpa. 
+ */
+public class MyEntityExampleTest extends MyEntityExampleTestBase {
+    // Empty, all tests are inherited
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/pom.xml b/tags/wamblee-utils-0.2.1/test/enterprise/pom.xml
new file mode 100644 (file)
index 0000000..d90bf3b
--- /dev/null
@@ -0,0 +1,70 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-test-enterprise</artifactId>
+  <packaging>jar</packaging>
+  <name>/test/enterprise</name>
+  <url>http://wamblee.org</url>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-support-general</artifactId>
+      <version>0.2.1</version>
+      <type>test-jar</type>
+    </dependency>
+    <dependency>
+      <groupId>javax.transaction</groupId>
+      <artifactId>transaction-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derby</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>mysql</groupId>
+      <artifactId>mysql-connector-java</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derbyclient</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.derby</groupId>
+      <artifactId>derbynet</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>commons-dbcp</groupId>
+      <artifactId>commons-dbcp</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>javax.persistence</groupId>
+      <artifactId>persistence-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.dbunit</groupId>
+      <artifactId>dbunit</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-jdk14</artifactId>
+    </dependency>
+  </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContext.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContext.java
new file mode 100644 (file)
index 0000000..a7e4c96
--- /dev/null
@@ -0,0 +1,31 @@
+package org.wamblee.support.jndi;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.naming.InitialContext;
+import javax.naming.Name;
+import javax.naming.NamingException;
+
+public class StubInitialContext extends InitialContext {
+       private Map<String, Object> bindings = new HashMap<String, Object>();
+
+       public StubInitialContext() throws NamingException { 
+               super(true);
+       }
+       
+       @Override
+       public void bind(String name, Object obj) throws NamingException {
+               bindings.put(name, obj);
+       }
+
+       @Override
+       public Object lookup(String name) throws NamingException {
+               return bindings.get(name);
+       }
+       
+       @Override
+       public Object lookup(Name name) throws NamingException {
+               return super.lookup(name.toString());
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContextFactory.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContextFactory.java
new file mode 100644 (file)
index 0000000..c7e4e2f
--- /dev/null
@@ -0,0 +1,63 @@
+package org.wamblee.support.jndi;
+
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.naming.spi.InitialContextFactory;
+
+/**
+ * Test initial context factory used for testing software in a Java SE
+ * environnment that uses JNDI to retrieve objects.
+ * 
+ * See {@link #bind(String, Object)} to resp. register the initial context.
+ * 
+ * To bind objects in the JNDI tree simply use the standard JNDI api: <code>
+ *   InitialContext context = new InitialContext();
+ *   MyClass myObj = ...; 
+ *   context.bind("a/b", myObj); 
+ * </code>
+ */
+public class StubInitialContextFactory implements InitialContextFactory {
+
+       private static Context context;
+
+       private static void initialize() {
+               try {
+                       context = new StubInitialContext();
+               } catch (NamingException e) { // can't happen.
+                       throw new RuntimeException(e);
+               }
+       }
+
+       /**
+        * This method must be called to register this initial context factory as
+        * the default implementation for JNDI.
+        * 
+        * @throws Exception
+        */
+       public static void register() {
+               // sets up the InitialContextFactoryForTest as default factory.
+               System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
+                               StubInitialContextFactory.class.getName());
+               if (context == null) {
+                       initialize();
+               }
+       }
+       
+       /**
+        * Unregisters the initial context factory 
+        */
+       public static void unregister() { 
+               System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
+               context = null; 
+       }
+
+       public Context getInitialContext(Hashtable<?, ?> environment)
+                       throws NamingException {
+               return context;
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabase.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabase.java
new file mode 100644 (file)
index 0000000..59f3d77
--- /dev/null
@@ -0,0 +1,78 @@
+package org.wamblee.support.persistence;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbcp.ConnectionFactory;
+import org.apache.commons.dbcp.DriverManagerConnectionFactory;
+import org.apache.commons.dbcp.PoolableConnectionFactory;
+import org.apache.commons.dbcp.PoolingDataSource;
+import org.apache.commons.pool.impl.GenericObjectPool;
+
+public abstract class AbstractDatabase implements Database {
+       private static final int CONNECTION_POOL_SIZE = 16;
+
+    private DataSource itsDataSource; 
+       
+       private boolean started; 
+       
+       protected AbstractDatabase() { 
+               started = false; 
+       }
+       
+       protected abstract void doStart();
+       
+       protected abstract void doStop();
+       
+       /**
+        * This method must be called from the start method. 
+        */
+       protected final void createDataSource() { 
+               GenericObjectPool connectionPool = new GenericObjectPool(null);
+               connectionPool.setMaxActive(CONNECTION_POOL_SIZE);
+               ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(getJdbcUrl(), getUsername(), getPassword());
+               // The following line must be kept in although it does not appear to be used, the constructor regsiters the
+               // constructed object at the connection pool. 
+               PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
+               itsDataSource = new PoolingDataSource(connectionPool);
+       }
+       
+       
+       /// BELOW THIS LINE IS NOT OF INTEREST TO SUBCLASSES.
+       
+       public final DataSource start() {
+               if ( started ) { 
+                       throw new RuntimeException("Database already started"); 
+               }
+               started = true; 
+               doStart();
+               return getDatasource();
+       }
+       
+       public final void stop() { 
+               if ( ! started ) { 
+                       return; // nothing to do. 
+               }
+               started = false;
+               doStop(); 
+       }
+
+       private final DataSource getDatasource() {
+               if ( !started) { 
+                       throw new RuntimeException("Database is not started!");
+               }
+               return itsDataSource;
+       }
+       
+       protected String getProperty(String aName) { 
+               String value = System.getProperty(aName); 
+               if ( value != null ) { 
+                       return value;
+               }
+               value = System.getenv(aName); 
+               if ( value != null ) { 
+                       return value; 
+               }
+               throw new RuntimeException("This class expects the '" + aName + "' property to be set");
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabaseProvider.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabaseProvider.java
new file mode 100644 (file)
index 0000000..6ed9d6c
--- /dev/null
@@ -0,0 +1,18 @@
+package org.wamblee.support.persistence;
+
+import java.util.List;
+
+public abstract class AbstractDatabaseProvider implements DatabaseProvider {
+
+       protected abstract List<String> getCapabilities(); 
+
+       public final boolean supportsCapabilities(String[] aCapabilities) {
+               for (String capability: aCapabilities) { 
+                       if ( !getCapabilities().contains(capability)) { 
+                               return false;
+                       }
+               }
+               return true; 
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaCustomizer.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaCustomizer.java
new file mode 100644 (file)
index 0000000..fc6ecc7
--- /dev/null
@@ -0,0 +1,33 @@
+package org.wamblee.support.persistence;
+
+import java.util.List;
+import java.util.Map;
+
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+public class CompositeJpaCustomizer implements JpaCustomizer {
+    
+    private List<JpaCustomizer> _customizers;
+    private CompositeJpaTables _tables; 
+    
+    public CompositeJpaCustomizer(List<JpaCustomizer> aCustomizers) { 
+        _customizers = aCustomizers;
+        _tables = new CompositeJpaTables();
+        for (JpaCustomizer customizer: _customizers) { 
+            _tables.add(customizer.getJpaTables());
+        }    
+    }
+    
+    @Override
+    public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+        for (JpaCustomizer customizer: _customizers) { 
+            customizer.customize(aPersistenceUnit, aJpaProperties); 
+        }
+    }
+
+    @Override
+    public ITableFilterSimple getJpaTables() {
+        return _tables; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaTables.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaTables.java
new file mode 100644 (file)
index 0000000..7a7e8de
--- /dev/null
@@ -0,0 +1,31 @@
+package org.wamblee.support.persistence;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+public class CompositeJpaTables implements ITableFilterSimple {
+    
+    private List<ITableFilterSimple> _tables; 
+    
+    public CompositeJpaTables() { 
+        _tables = new ArrayList<ITableFilterSimple>();
+    }
+    
+    public void add(ITableFilterSimple aFilter) { 
+        _tables.add(aFilter);
+    }
+
+    @Override
+    public boolean accept(String aTableName) throws DataSetException {
+        for (ITableFilterSimple filter: _tables) { 
+            if (filter.accept(aTableName)) { 
+                return true; 
+            }
+        }
+        return false; 
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/Database.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/Database.java
new file mode 100755 (executable)
index 0000000..f37474e
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright 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.wamblee.support.persistence;
+
+import javax.sql.DataSource;
+
+/**
+ * Represents a database.
+ * 
+ * @author Erik Brakkee
+ */
+public interface Database {
+       
+    /**
+     * Starts a database. This call should not block and return as soon as the
+     * database has been started.
+     */
+    DataSource start();
+    
+    /**
+     * Gets the Jdbc Url to connect to this database.
+     * 
+     * @return Jdbc Url.
+     */
+    String getJdbcUrl();
+
+    /**
+     * Gets the external Jdbc URL to connect to this database from other JVMs.
+     */
+    String getExternalJdbcUrl();
+
+    /**
+     * Gets the username to connect to the database.
+     * 
+     * @return username.
+     */
+    String getUsername();
+
+    /**
+     * Gets the password to connect to the database.
+     * 
+     * @return password.
+     */
+    String getPassword();
+
+    /**
+     * Stops a database.
+     */
+    void stop();
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseBuilder.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseBuilder.java
new file mode 100644 (file)
index 0000000..9c599a0
--- /dev/null
@@ -0,0 +1,116 @@
+package org.wamblee.support.persistence;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.ServiceLoader;
+import java.util.logging.Logger;
+
+/**
+ * DatabaseBuilder is used from unit test to obtain a reference to a database
+ * from unit test. This database is either an inmemory database or represents an
+ * external database. Purpose of this utility is to make test code independent of the 
+ * particular database used and specifically to be able to run database tests without 
+ * any configuration at all (using an inmemory database).  
+ * 
+ * The type of database to use can be overridden by specifying either a system
+ * property or an environment variable ({@link #DB_CAPABILITIES_PROP}) that
+ * contains the comma-separated capabilities of the database. Each database type
+ * provides its own capabilities (see {@link DatabaseProvider} implementations}.
+ * 
+ * 
+ * There are currently two database types available: 
+ * <ul>
+ *   <li> Derby: AN inmemory derby. Provided by {@link DerbyDatabaseProvider}. This is the default. 
+ *   </li>
+ *   <li> External: An arbitrary external database configured using system properties or environment variables
+ *     in the usual way using a JDBC URL, username, and password. 
+ *   </li>
+ * </ul>
+ * 
+ * The <code>DatabaseBuilder</code> uses the {@link ServiceLoader} mechanism to find implementations
+ * of {@link DatabaseProvider} on the classpath. In the {@link #getDatabase(String...)} method a number of 
+ * capabilities are passed. The database providers are then searched in (arbitrary) order and the first one that
+ * has all required capabilities is returned. 
+ * 
+ * {@link #getSupportedDatabases()} gives a list of all available databases. 
+ */
+public class DatabaseBuilder {
+
+       private static final Logger LOGGER = Logger.getLogger(DatabaseBuilder.class
+                       .getName());
+
+       /**
+        * Environmment variable by which capabilities of the requested database can
+        * be defined
+        */
+       private static final String DB_CAPABILITIES_PROP = "TEST_DB_CAPABILITIES";
+
+       private static ServiceLoader<DatabaseProvider> LOADER = null;
+
+       private DatabaseBuilder() {
+               // Empty.
+       }
+
+       private static String[] parseCapabilities(String aValue) {
+               return aValue.split(",");
+       }
+
+       /**
+        * Gets the first database that has all required capabilities. 
+        * @param aCapabilities Capabilities. 
+        * @return Database to use. 
+        */
+       public static Database getDatabase(String... aCapabilities) {
+               if (aCapabilities.length == 0) {
+                       LOGGER.info("Examining database capabilities");
+                       LOGGER.info("  Checking system property " + DB_CAPABILITIES_PROP);
+                       String capabilities = System.getProperty(DB_CAPABILITIES_PROP);
+                       if (capabilities != null) {
+                               aCapabilities = parseCapabilities(capabilities);
+                       } else {
+                               LOGGER.info("  Checking environment variable "
+                                               + DB_CAPABILITIES_PROP);
+                               capabilities = System.getenv(DB_CAPABILITIES_PROP);
+                               if (capabilities != null) {
+                                       aCapabilities = parseCapabilities(capabilities);
+                               } else {
+                                       LOGGER.info("  Using default capabilities");
+                                       aCapabilities = new String[] { DatabaseProvider.CAPABILITY_IN_MEMORY };
+                               }
+                       }
+                       LOGGER.info("Using capabilities: " + aCapabilities);
+               }
+               synchronized (DatabaseBuilder.class) {
+                       initLoader();
+                       for (DatabaseProvider db : LOADER) {
+                               if (db.supportsCapabilities(aCapabilities)) {
+                                       return db.create();
+                               }
+                       }
+               }
+               throw new RuntimeException(
+                               "No database found that satisfies capabilities: "
+                                               + Arrays.asList(aCapabilities));
+       }
+
+       /**
+        * Gets a list of available databases. 
+        * @return List of databases. 
+        */
+       public static List<DatabaseDescription> getSupportedDatabases() {
+               initLoader();
+               List<DatabaseDescription> descriptions = new ArrayList<DatabaseDescription>();
+               for (DatabaseProvider db : LOADER) {
+                       descriptions.add(db.getDescription());
+               }
+               return descriptions;
+       }
+
+       private static void initLoader() {
+               if (LOADER == null) {
+                       LOADER = ServiceLoader.load(DatabaseProvider.class);
+               }
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseDescription.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseDescription.java
new file mode 100644 (file)
index 0000000..c31427b
--- /dev/null
@@ -0,0 +1,41 @@
+package org.wamblee.support.persistence;
+
+/**
+ * Description of a specific database. 
+ */
+public class DatabaseDescription {
+
+       private String[] itsCapabilities; 
+       private String itsDatabase; 
+       private String itsOther;
+       
+       /**
+        * Constructs the description. 
+        * @param aCapabilities List of all capabilities. 
+        * @param aDatabase Database. 
+        * @param aOther Other information. 
+        */
+       public DatabaseDescription(String[] aCapabilities, String aDatabase, String aOther) {
+               itsCapabilities = aCapabilities; 
+               itsDatabase = aDatabase; 
+               itsOther = aOther;
+       }
+       
+       @Override
+       public String toString() {
+               return "\n  Database " + itsDatabase + 
+                               "\n    Capabilities: "  + printCapabilities() + 
+                               "\n    Other info:   " + itsOther; 
+       }
+       
+       private String printCapabilities() {
+               String res = "";
+               for (int i = 0; i < itsCapabilities.length; i++) { 
+                       res += "" + itsCapabilities[i]; 
+                       if ( i < itsCapabilities.length -1 ) { 
+                               res += ", ";
+                       }
+               }
+               return res; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseProvider.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseProvider.java
new file mode 100644 (file)
index 0000000..f6736aa
--- /dev/null
@@ -0,0 +1,42 @@
+package org.wamblee.support.persistence;
+
+/**
+ * Database provider. This database provider represents a particular type of
+ * database such as its capabilities and the ability to create an instance
+ * representing a running database.
+ * 
+ * Since the {@link DatabaseBuilder} uses a first match algorithm and the order
+ * of databaseproviders is not guaranteed, it is recommended for each database
+ * provider to also provide a unique capability that no other database has.
+ */
+public interface DatabaseProvider {
+
+       /**
+        * Capability that all databases that run inmemory have.
+        */
+       String CAPABILITY_IN_MEMORY = "INMEMORY";
+
+       /**
+        * Capability that all databases that are external have.
+        */
+       String CAPABILITY_EXTERNAL = "EXTERNAL";
+
+       /**
+        * Determines if the database has all capabilities that are requested.
+        * @param aCapabilities Capabilities it must ahve
+        * @return True if it has all capabilities. 
+        */
+       boolean supportsCapabilities(String[] aCapabilities);
+
+       /**
+        * Gets the description for the database. 
+        * @return Description.
+        */
+       DatabaseDescription getDescription();
+
+       /**
+        * Creates a database instance that represents a running instance of that database. 
+        * @return Database. 
+        */
+       Database create();
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseStarter.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseStarter.java
new file mode 100644 (file)
index 0000000..44294e3
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright 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.wamblee.support.persistence;
+
+
+/**
+ * This class is used for starting the database from ant.
+ */
+public class DatabaseStarter {
+
+    /**
+     * Database class which encapsulates management of the database.
+     */
+    private Class _databaseClass;
+
+    /**
+     * Execution as a main program. Commandline
+     * 
+     * <pre>
+     * 
+     *    DatabaseStarter &lt;databaseClassName&gt;
+     *  
+     * </pre>
+     * 
+     * where the database class name must be the name of a concrete subclass of
+     * {@link Database}.
+     * 
+     * @param args
+     */
+    public static void main( String[] args ) throws Exception {
+        String clazz = args[0];
+        try {
+            new DatabaseStarter( Class.forName( clazz ) ).start( );
+        } catch ( Exception e ) {
+            e.printStackTrace( );
+            System.out
+                    .println( "\nUsage: ant dbClass ");
+        }
+    }
+
+    /**
+     * Constructs the database starter.
+     * 
+     * @param aClassName
+     *            Classname of the database class to use.
+     * @throws Exception
+     */
+    public DatabaseStarter( Class aClass ) throws Exception {
+        if ( !Database.class.isAssignableFrom( aClass ) ) {
+            throw new IllegalArgumentException( "Class '"
+                    + aClass.getName( )
+                    + "' is not a subclass of Database" );
+        }
+        _databaseClass = aClass;
+    }
+
+    /**
+     * Constructs a database starter with the derby database.
+     * 
+     * @throws Exception
+     */
+    public DatabaseStarter( ) throws Exception {
+        this( DerbyDatabase.class );
+    }
+
+    /**
+     * Starts the database.
+     * 
+     * @throws Exception
+     */
+    public void start( ) throws Exception {
+        Database lDatabase = (Database) _databaseClass.newInstance( );
+        lDatabase.start( );
+        System.out.println( "Database has been started. " );
+        System.out.println( );
+        System.out.println("=======================================================");
+        System.out.println( "Connection details:" );
+       // System.out.println( "  Driver class: "
+       //         + lDatabase.getDriverClassName( ) );
+        System.out.println( "  JDBC URL:     "
+                + lDatabase.getExternalJdbcUrl( ) );
+        System.out.println( "  username:     '" + lDatabase.getUsername( )
+                + "'" );
+        System.out.println( "  password:     '" + lDatabase.getPassword( )
+                + "'" );
+        System.out.println( "Interrupt the program to stop the database." );
+        System.out.println("=======================================================");
+        System.out.println("You must now populate the database with a schema. Use 'ant help' for information.");
+        for ( ;; ) {
+            Thread.sleep( 1000 );
+        }
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseUtils.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseUtils.java
new file mode 100644 (file)
index 0000000..312e38a
--- /dev/null
@@ -0,0 +1,389 @@
+package org.wamblee.support.persistence;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Logger;
+
+import javax.sql.DataSource;
+
+import junit.framework.TestCase;
+
+import org.dbunit.DataSourceDatabaseTester;
+import org.dbunit.IDatabaseTester;
+import org.dbunit.database.DatabaseConnection;
+import org.dbunit.database.DatabaseSequenceFilter;
+import org.dbunit.database.IDatabaseConnection;
+import org.dbunit.dataset.FilteredDataSet;
+import org.dbunit.dataset.IDataSet;
+import org.dbunit.dataset.filter.ITableFilter;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.dbunit.operation.DatabaseOperation;
+
+/**
+ * Database utilities is a simple support class for common tasks in working with
+ * databases.
+ */
+public class DatabaseUtils {
+
+       public static interface TableSet {
+               boolean contains(String aTableName);
+       }
+
+       public static interface JdbcUnitOfWork<T> {
+               T execute(Connection aConnection) throws Exception;
+       }
+
+       public static interface TableSetOperation {
+               void execute(String aTable) throws Exception;
+       }
+
+       private static final Logger LOG = Logger.getLogger(DatabaseUtils.class
+                       .getName());
+
+       /**
+        * Schema pattern.
+        */
+       private static final String SCHEMA_PATTERN = "%";
+       private DataSource dataSource;
+       private ITableFilterSimple tables;
+       
+
+       public DatabaseUtils(DataSource aDataSource, ITableFilterSimple aTables) {
+               dataSource = aDataSource;
+               tables = aTables;
+       }
+
+       public IDatabaseTester createDbTester() throws Exception {
+               return createDbTester(getTableNames(tables));
+       }
+
+       public IDatabaseTester createDbTester(String[] aTables) throws Exception {
+               IDatabaseTester dbtester = new DataSourceDatabaseTester(dataSource);
+               dbtester.setDataSet(dbtester.getConnection().createDataSet(aTables));
+               return dbtester;
+       }
+
+       public void cleanDatabase() throws Exception {
+               cleanDatabase(tables);
+       }
+
+       public void executeOnTables(ITableFilterSimple aTables,
+                       final TableSetOperation aOperation) throws Exception {
+               final String[] tables = getTableNames(aTables);
+               executeInTransaction(new JdbcUnitOfWork<Void>() {
+                       public Void execute(Connection aConnection) throws Exception {
+                               for (int i = tables.length - 1; i >= 0; i--) {
+                                       aOperation.execute(tables[i]);
+                               }
+                               return null;
+                       }
+               });
+               for (String table : tables) {
+
+               }
+       }
+
+       public void cleanDatabase(ITableFilterSimple aSelection) throws Exception {
+
+               final String[] tables = getTableNames(aSelection);
+               executeInTransaction(new JdbcUnitOfWork<Void>() {
+
+                       public Void execute(Connection aConnection) throws Exception {
+                               IDatabaseConnection connection = new DatabaseConnection(
+                                               aConnection);
+                               ITableFilter filter = new DatabaseSequenceFilter(connection,
+                                               tables);
+                               IDataSet dataset = new FilteredDataSet(filter, connection
+                                               .createDataSet(tables));
+                               DatabaseOperation.DELETE_ALL.execute(connection, dataset);
+                               return null;
+                       }
+               });
+
+       }
+
+       public <T> T executeInTransaction(JdbcUnitOfWork<T> aCallback)
+                       throws Exception {
+               Connection connection = dataSource.getConnection();
+               try {
+                       T value = aCallback.execute(connection);
+                       connection.commit();
+                       return value;
+               } finally {
+                       connection.close();
+               }
+       }
+
+       public String[] getTableNames() throws Exception {
+               return getTableNames(tables);
+       }
+
+       /**
+        * @throws SQLException
+        */
+       public String[] getTableNames(ITableFilterSimple aSelection)
+                       throws Exception {
+
+               List<String> result = new ArrayList<String>();
+               LOG.fine("Getting database table names to clean (schema: '"
+                               + SCHEMA_PATTERN + "'");
+
+               ResultSet tables = dataSource.getConnection().getMetaData().getTables(
+                               null, SCHEMA_PATTERN, "%", new String[] { "TABLE" });
+               while (tables.next()) {
+                       String table = tables.getString("TABLE_NAME");
+                       if (aSelection.accept(table)) {
+                               result.add(table);
+                       }
+               }
+               return (String[]) result.toArray(new String[0]);
+       }
+
+       public void emptyTables() throws Exception {
+               executeOnTables(tables, new TableSetOperation() {
+                       public void execute(String aTable) throws Exception {
+                               emptyTable(aTable);
+                       }
+               });
+       }
+
+       /**
+        * @return
+        * @throws SQLException
+        */
+       public void emptyTables(final ITableFilterSimple aSelection)
+                       throws Exception {
+               executeOnTables(aSelection, new TableSetOperation() {
+                       public void execute(String aTable) throws Exception {
+                               emptyTable(aTable);
+                       }
+               });
+       }
+
+       /**
+        * @return
+        * @throws SQLException
+        */
+       public void emptyTable(String aTable) throws Exception {
+               executeSql("delete from " + aTable);
+       }
+       
+       public void dropTables() throws Exception {
+               executeOnTables(tables, new TableSetOperation() {
+                       
+                       public void execute(String aTable) throws Exception {
+                               dropTable(aTable);      
+                       }
+               });
+       }
+
+       
+       public void dropTables(ITableFilterSimple aTables) throws Exception {
+               executeOnTables(aTables, new TableSetOperation() {
+                       
+                       public void execute(String aTable) throws Exception {
+                               dropTable(aTable);      
+                       }
+               });
+       }
+
+       /**
+        * @return
+        * @throws SQLException
+        */
+       public void dropTable(final String aTable) throws Exception {
+               executeInTransaction(new JdbcUnitOfWork<Void>() {
+                       public Void execute(Connection aConnection) throws Exception {
+                               executeUpdate(aConnection, "drop table " + aTable);
+                               return null;
+                       }
+               });
+
+       }
+
+       /**
+        * Executes an SQL statement within a transaction.
+        * 
+        * @param aSql
+        *            SQL statement.
+        * @return Return code of the corresponding JDBC call.
+        */
+       public int executeSql(final String aSql) throws Exception {
+               return executeSql(aSql, new Object[0]);
+       }
+
+       /**
+        * Executes an SQL statement within a transaction. See
+        * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+        * supported argument types.
+        * 
+        * @param aSql
+        *            SQL statement.
+        * @param aArg
+        *            Argument of the sql statement.
+        * @return Return code of the corresponding JDBC call.
+        */
+       public int executeSql(final String aSql, final Object aArg)
+                       throws Exception {
+               return executeSql(aSql, new Object[] { aArg });
+       }
+
+       /**
+        * Executes an sql statement. See
+        * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+        * supported argument types.
+        * 
+        * @param aSql
+        *            SQL query to execute.
+        * @param aArgs
+        *            Arguments.
+        * @return Number of rows updated.
+        */
+       public int executeSql(final String aSql, final Object[] aArgs)
+                       throws Exception {
+               return executeInTransaction(new JdbcUnitOfWork<Integer>() {
+                       public Integer execute(Connection aConnection) throws Exception {
+                               PreparedStatement stmt = aConnection.prepareStatement(aSql);
+                               setPreparedParams(aArgs, stmt);
+                               return stmt.executeUpdate();
+                       }
+               });
+       }
+
+       /**
+        * Executes an SQL query.
+        * 
+        * @param aSql
+        *            Query to execute.
+        * @return Result set.
+        */
+       public ResultSet executeQuery(Connection aConnection, String aSql) {
+               return executeQuery(aConnection, aSql, new Object[0]);
+       }
+
+       /**
+        * Executes a query with a single argument. See
+        * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+        * supported argument types.
+        * 
+        * @param aSql
+        *            Query.
+        * @param aArg
+        *            Argument.
+        * @return Result set.
+        */
+       public ResultSet executeQuery(Connection aConnection, String aSql,
+                       Object aArg) {
+               return executeQuery(aConnection, aSql, new Object[] { aArg });
+       }
+
+       /**
+        * Executes a query. See
+        * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+        * supported argument types.
+        * 
+        * @param aSql
+        *            Sql query.
+        * @param aArgs
+        *            Arguments to the query.
+        * @return Result set.
+        */
+       public ResultSet executeQuery(Connection aConnection, final String aSql,
+                       final Object[] aArgs) {
+               try {
+                       PreparedStatement statement = aConnection.prepareStatement(aSql);
+                       setPreparedParams(aArgs, statement);
+
+                       return statement.executeQuery();
+               } catch (SQLException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+       
+       public int executeUpdate(Connection aConnection, final String aSql,
+                       final Object... aArgs) {
+               try {
+                       PreparedStatement statement = aConnection.prepareStatement(aSql);
+                       setPreparedParams(aArgs, statement);
+
+                       return statement.executeUpdate();
+               } catch (SQLException e) {
+                       throw new RuntimeException(e);
+               }
+       }
+
+       /**
+        * Sets the values of a prepared statement. See
+        * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on
+        * supported argument types.
+        * 
+        * @param aArgs
+        *            Arguments to the prepared statement.
+        * @param aStatement
+        *            Prepared statement
+        * @throws SQLException
+        */
+       private void setPreparedParams(final Object[] aArgs,
+                       PreparedStatement aStatement) throws SQLException {
+               for (int i = 1; i <= aArgs.length; i++) {
+                       setPreparedParam(i, aStatement, aArgs[i - 1]);
+               }
+       }
+
+       /**
+        * Sets a prepared statement parameter.
+        * 
+        * @param aIndex
+        *            Index of the parameter.
+        * @param aStatement
+        *            Prepared statement.
+        * @param aObject
+        *            Value Must be of type Integer, Long, or String.
+        * @throws SQLException
+        */
+       private void setPreparedParam(int aIndex, PreparedStatement aStatement,
+                       Object aObject) throws SQLException {
+               if (aObject instanceof Integer) {
+                       aStatement.setInt(aIndex, ((Integer) aObject).intValue());
+               } else if (aObject instanceof Long) {
+                       aStatement.setLong(aIndex, ((Integer) aObject).longValue());
+               } else if (aObject instanceof String) {
+                       aStatement.setString(aIndex, (String) aObject);
+               } else {
+                       TestCase.fail("Unsupported object type for prepared statement: "
+                                       + aObject.getClass() + " value: " + aObject
+                                       + " statement: " + aStatement);
+               }
+       }
+
+       /**
+        * @return
+        * @throws SQLException
+        */
+       public int getTableSize(final String aTable) throws Exception {
+               return executeInTransaction(new JdbcUnitOfWork<Integer>() {
+                       public Integer execute(Connection aConnection) throws Exception {
+                               ResultSet resultSet = executeQuery(aConnection,
+                                               "select count(*) from " + aTable);
+                               resultSet.next();
+                               return resultSet.getInt(1);
+                       }
+               });
+
+       }
+
+       public int countResultSet(ResultSet aResultSet) throws SQLException {
+               int count = 0;
+
+               while (aResultSet.next()) {
+                       count++;
+               }
+
+               return count;
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabase.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabase.java
new file mode 100755 (executable)
index 0000000..646931c
--- /dev/null
@@ -0,0 +1,314 @@
+/*
+ * Copyright 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.wamblee.support.persistence;
+
+import java.io.File;
+import java.io.PrintWriter;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import junit.framework.TestCase;
+
+import org.apache.derby.drda.NetworkServerControl;
+import org.wamblee.io.FileSystemUtils;
+
+/**
+ * Derby database setup. The external JDBC url used to connect to a running
+ * instance is
+ * 
+ * <pre>
+ *     jdbc:derby:net://localhost:1527/testdb
+ * </pre>
+ * 
+ * and the driver class is
+ * 
+ * <pre>
+ * com.ibm.db2.jcc.DB2Driver
+ * </pre>
+ * 
+ * The following jars will have to be used <code>db2jcc.jar</code> and
+ * <code>db2jcc_license_c.jar</code>.
+ */
+public class DerbyDatabase extends AbstractDatabase {
+
+       /**
+        * Logger.
+        */
+       private static final Logger LOGGER = Logger.getLogger(DerbyDatabase.class
+                       .getName());
+
+       /**
+        * Database user name.
+        */
+       private static final String USERNAME = "sa";
+
+       /**
+        * Database password.
+        */
+       private static final String PASSWORD = "123";
+       /**
+        * Poll interval for the checking the server status.
+        */
+       private static final int POLL_INTERVAL = 100;
+
+       /**
+        * Maximum time to wait until the server has started or stopped.
+        */
+       private static final int MAX_WAIT_TIME = 10000;
+
+       /**
+        * Database name to use.
+        */
+       private static final String DATABASE_NAME = "testdb";
+
+       /**
+        * Path on the file system where derby files are stored.
+        */
+       private static final String DATABASE_PATH = "target/db/persistence/derby";
+
+       /**
+        * Derby property required to set the file system path
+        * {@link #DATABASE_PATH}.
+        */
+       private static final String SYSTEM_PATH_PROPERTY = "derby.system.home";
+       
+
+       private boolean inmemory;
+               
+       
+       /**
+        * Constructs derby database class to allow creation of derby database
+        * instances.
+        */
+       public DerbyDatabase() {
+               inmemory = true;
+       }
+
+       public DerbyDatabase(boolean aInMemoryFlag) {
+               inmemory = aInMemoryFlag;
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.wamblee.persistence.Database#start()
+        */
+       public void doStart() {
+               try {
+                       // just in case a previous run was killed without the
+                       // cleanup
+                       cleanPersistentStorage();
+
+                       if (!inmemory) {
+                               // set database path.
+                               Properties lProperties = System.getProperties();
+                               lProperties.put(SYSTEM_PATH_PROPERTY, DATABASE_PATH);
+                       }
+
+                       Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
+
+                       runDatabase();
+
+                       waitUntilStartedOrStopped(true);
+
+                       // Force creation of the database.
+                       Connection lConnection = createConnection();
+                       lConnection.close();
+                       
+                       LOGGER.info("Database started: \n    URL = " + getExternalJdbcUrl() + "\n    user = " + getUsername() + "\n    password = " 
+                                       + getPassword()); 
+
+                       createDataSource();
+                       
+                       Runtime.getRuntime().addShutdownHook(new Thread() {
+                               @Override
+                               public void run() {
+                                       if (isStarted()) {
+                                               LOGGER.warning("Shutting down db");
+                                               DerbyDatabase.this.stop();
+                                       }
+                               }
+                       });
+               } catch (Exception e) {
+                       throw new RuntimeException("Problem starting database", e);
+               }
+       }
+
+       /**
+        * Waits until the database server has started or stopped.
+        * 
+        * @param aStarted
+        *            If true, waits until the server is up, if false, waits until
+        *            the server is down.
+        * @throws InterruptedException
+        */
+       private void waitUntilStartedOrStopped(boolean aStarted)
+                       throws InterruptedException {
+               long lWaited = 0;
+
+               while (aStarted != isStarted()) {
+                       Thread.sleep(POLL_INTERVAL);
+                       lWaited += POLL_INTERVAL;
+
+                       if (lWaited > MAX_WAIT_TIME) {
+                               throw new RuntimeException(
+                                               "Derby database did not start within " + MAX_WAIT_TIME
+                                                               + "ms");
+                       }
+               }
+       }
+
+       /**
+        * Checks if the database server has started or not.
+        * 
+        * @return True if started, false otherwise.
+        */
+       private boolean isStarted() {
+               try {
+                       getControl().ping();
+
+                       return true;
+               } catch (Exception e) {
+                       return false;
+               }
+       }
+
+       /**
+        * Gets the controller for the database server.
+        * 
+        * @return Controller.
+        * @throws Exception
+        */
+       private NetworkServerControl getControl() throws Exception {
+               return new NetworkServerControl();
+       }
+
+       /**
+        * Runs the database.
+        * 
+        */
+       private void runDatabase() {
+               try {
+                       getControl().start(new PrintWriter(System.out));
+               } catch (Exception e) {
+                       throw new RuntimeException(e);
+               }
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.wamblee.persistence.Database#getJdbcUrl()
+        */
+       public String getJdbcUrl() {
+               return getBaseJdbcUrl()
+                               + ";create=true;retrieveMessagesFromServerOnGetMessage=true;";
+       }
+
+       private String getBaseJdbcUrl() {
+               return (inmemory ? "jdbc:derby:memory:": "jdbc:derby:") + DATABASE_NAME;
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.wamblee.persistence.Database#getExternalJdbcUrl()
+        */
+       public String getExternalJdbcUrl() {
+               return "jdbc:derby://localhost:1527/" + (inmemory ? "memory:" : "") + DATABASE_NAME;
+       }
+
+       /**
+        * Shuts down the derby database and cleans up all created files.
+        * 
+        */
+       private void shutdownDerby() {
+               try {
+                       DriverManager.getConnection("jdbc:derby:;shutdown=true");
+                       throw new RuntimeException("Derby did not shutdown, "
+                                       + " should always throw exception at shutdown");
+               } catch (Exception e) {
+                       LOGGER.info("Derby has been shut down.");
+               }
+       }
+
+       /**
+        * Gets the user name.
+        */
+       public String getUsername() {
+               return USERNAME;
+       }
+
+       /**
+        * Gets the password.
+        * 
+        * @return
+        */
+       public String getPassword() {
+               return PASSWORD;
+       }
+
+       /*
+        * (non-Javadoc)
+        * 
+        * @see org.wamblee.persistence.Database#createConnection()
+        */
+       public Connection createConnection() throws SQLException {
+               Connection c = DriverManager.getConnection(getJdbcUrl(), getUsername(),
+                               getPassword());
+
+               return c;
+       }
+
+
+       /**
+        * Stops the derby database and cleans up all derby files.
+        */
+       public void doStop() {
+               try {
+                       // shutdown network server.
+                       getControl().shutdown();
+                       waitUntilStartedOrStopped(false);
+
+                       // shutdown inmemory access.
+                       shutdownDerby();
+                       cleanPersistentStorage();
+               } catch (Exception e) {
+                       LOGGER.log(Level.WARNING, "Problem stopping database", e);
+               }
+       }
+
+       /**
+        * Cleans up persistent storage of Derby.
+        */
+       private void cleanPersistentStorage() {
+               File lFile = new File(DATABASE_PATH);
+
+               if (lFile.isFile()) {
+                       TestCase.fail("A regular file by the name " + DATABASE_PATH
+                                       + " exists, clean this up first");
+               }
+
+               if (!lFile.isDirectory()) {
+                       return; // no-op already cleanup up.
+               }
+               FileSystemUtils.deleteDirRecursively(DATABASE_PATH);
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java
new file mode 100644 (file)
index 0000000..088202c
--- /dev/null
@@ -0,0 +1,32 @@
+package org.wamblee.support.persistence;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class DerbyDatabaseProvider extends AbstractDatabaseProvider {
+       
+       /**
+        * Capabilities of this type of database. 
+        */
+       public static final List<String> CAPABILIITIES = 
+               Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY, "DERBY");
+
+
+       public DerbyDatabaseProvider() {
+               // Empty
+       }
+
+       public Database create() {
+               return new DerbyDatabase();
+       }
+
+       public DatabaseDescription getDescription() {
+               return new DatabaseDescription(CAPABILIITIES.toArray(new String[0]),
+                               "Derby", "In-memory, volatile, set breakpoint to debug");
+       }
+
+    @Override
+    protected List<String> getCapabilities() {
+       return CAPABILIITIES;
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabase.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabase.java
new file mode 100644 (file)
index 0000000..2533df4
--- /dev/null
@@ -0,0 +1,82 @@
+package org.wamblee.support.persistence;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.logging.Logger;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbcp.ConnectionFactory;
+import org.apache.commons.dbcp.DriverManagerConnectionFactory;
+import org.apache.commons.dbcp.PoolableConnectionFactory;
+import org.apache.commons.dbcp.PoolingDataSource;
+import org.apache.commons.pool.impl.GenericObjectPool;
+
+/**
+ * Database that encapsulates connection to an external database. 
+ * Database connection details can be configured through system properties
+ * and environment variables, see {@link #DB_URL_PROP}, {@link #DB_USER_PROP}, and 
+ * {@link #DB_PASSWORD_PROP|. 
+ * 
+ * This class assumes modern database drivers that work together with java.util.ServiceLoader
+ * so that explicitly doing a Class.forName() is not necessary to load the database driver. 
+ */
+public class ExternalDatabase extends AbstractDatabase {
+       
+       private static final Logger LOGGER = Logger.getLogger(ExternalDatabase.class.getName()); 
+       
+       /**
+        * System property/environment variable that defines the database URL. 
+        */
+       public static final String DB_URL_PROP = "TEST_DB_URL";
+       
+       /**
+        * System property/environment variable that defines the database user. 
+        */
+       public static final String DB_USER_PROP = "TEST_DB_USER";
+       
+       /**
+        * System property/environment variable that defines the database password. 
+        */
+       public static final String DB_PASSWORD_PROP = "TEST_DB_PASSWORD";
+
+
+       private String itsUrl; 
+       private String itsUser; 
+       private String itsPassword; 
+       
+       private DataSource itsDataSource; 
+       
+       public ExternalDatabase() { 
+               // Empty
+       }
+       
+       public String getExternalJdbcUrl() {
+               return itsUrl; 
+       }
+
+       public String getJdbcUrl() {
+               return itsUrl; 
+       }
+
+       public String getPassword() {
+               return itsPassword;
+       }
+
+       public String getUsername() {
+               return itsUser;
+       }
+
+       public void doStart() {
+               itsUrl = getProperty(DB_URL_PROP);
+               itsUser = getProperty(DB_USER_PROP);
+               itsPassword = getProperty(DB_PASSWORD_PROP);
+               
+               createDataSource();
+       }
+
+       public void doStop() {
+               // Empty. 
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabaseProvider.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabaseProvider.java
new file mode 100644 (file)
index 0000000..871be11
--- /dev/null
@@ -0,0 +1,35 @@
+package org.wamblee.support.persistence;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class ExternalDatabaseProvider extends AbstractDatabaseProvider {
+
+       /**
+        * Capabilities of this type of database.
+        */
+       public static final List<String> CAPABILIITIES = Arrays
+                       .asList(CAPABILITY_EXTERNAL);
+
+       @Override
+       protected List<String> getCapabilities() {
+               return CAPABILIITIES;
+       }
+
+       public Database create() {
+               return new ExternalDatabase();
+       }
+
+       public DatabaseDescription getDescription() {
+               return new DatabaseDescription(
+                               CAPABILIITIES.toArray(new String[0]),
+                               "External Database",
+                               "Any database as described by the JDBC URL: requires system properties or environment variables: "
+                                               + ExternalDatabase.DB_URL_PROP
+                                               + ", "
+                                               + ExternalDatabase.DB_USER_PROP
+                                               + ", and "
+                                               + ExternalDatabase.DB_PASSWORD_PROP);
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaBuilder.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaBuilder.java
new file mode 100644 (file)
index 0000000..8b6e339
--- /dev/null
@@ -0,0 +1,136 @@
+package org.wamblee.support.persistence;
+
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import javax.sql.DataSource;
+
+import org.wamblee.support.jndi.StubInitialContextFactory;
+
+
+/**
+ * Utility for building an appropriately configured EntityManagerFactory. The
+ * idea is that a persistence.xml is used unchanged from the production version.
+ * This utility will then add the additional properties required for execution
+ * in a standalone environment.
+ * 
+ * The other purpose is to to shield dependencies of the test code on a
+ * particular JPA provider.
+ */
+public class JpaBuilder {
+
+       private static final Logger LOGGER = Logger.getLogger(JpaBuilder.class
+                       .getName());
+
+       /**
+        * Callback interface to execute some JPA code within a transaction with the
+        * entitymanager to use provided as input.
+        */
+       public static interface JpaUnitOfWork<T> {
+               /**
+                * Executes the unit of work. A transaction has been started.  
+                * @param em Entity manager. 
+                * @return Result of the execute method. If you don't want to return anything use
+                *  <code>Void</code> for the return type and return null from the implementation. 
+                */
+               T execute(EntityManager em);
+       }
+
+       private PersistenceUnitDescription persistenceUnit;
+       private DataSource dataSource;
+       private EntityManagerFactory factory;
+
+       /**
+        * Constructs the builder.
+        * 
+        * @param aDataSource
+        *            Datasource of database.
+        * @param aPersistenceUnit
+        *            Persistence unit.
+        */
+       public JpaBuilder(DataSource aDataSource,
+                       PersistenceUnitDescription aPersistenceUnit) {
+               persistenceUnit = aPersistenceUnit;
+               dataSource = aDataSource;
+               StubInitialContextFactory.register();
+       }
+
+       /**
+        * Starts the builder, which in particular, mocks JNDI, binds the datasource
+        * the JNDI where the persistence unit expects it, creates the entity
+        * manager factory, and forces creation of the database schema.
+        */
+       public void start() throws Exception {
+               try {
+                       InitialContext ctx = new InitialContext();
+                       ctx.bind(persistenceUnit.getJndiName(), dataSource);
+               } catch (NamingException e) {
+                       throw new RuntimeException("JNDI problem", e);
+               }
+               factory = createFactory();
+               execute(new JpaUnitOfWork<Void>() {
+                       public Void execute(EntityManager em) {
+                               // Empty, just to trigger database schema creation.
+                               return null;
+                       }
+               });
+       }
+
+       /**
+        * Stops the entity manager factory and disables JNDI mocking. 
+        */
+       public void stop() {
+               StubInitialContextFactory.unregister();
+               factory.close();
+       }
+
+       /**
+        * Creates a new entity manager factory. Typically not used by test code. 
+        * @return Entity manager factory. 
+        */
+       public EntityManagerFactory createFactory() {
+               Map<String, String> jpaProps = new TreeMap<String, String>();
+       
+               JpaCustomizerBuilder.getCustomizer().customize(persistenceUnit, jpaProps);
+               
+               //jpaProps.put("javax.persistence.provider", HibernatePersistence.class.getName());
+               EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnit
+                               .getUnitName(), jpaProps);
+               
+               LOGGER.info("Using " + factory.getClass());
+               return factory;
+       }
+
+       /**
+        * Executes a unit of work. This creates an entitymanager and runs the 
+        * {@link JpaUnitOfWork#execute(EntityManager)} within a transaction, passing
+        * it the entity manager. Use of this method saves a lot of typing for applications. 
+        * 
+        * @param aWork Work to execute. 
+        * @return The return value of the execute method of the unit of work. 
+        */
+       public <T> T execute(JpaUnitOfWork<T> aWork) throws Exception {
+               EntityManager em = factory.createEntityManager();
+               EntityTransaction transaction = em.getTransaction();
+               transaction.begin();
+               try {
+                       T value = aWork.execute(em);
+                       transaction.commit();
+                       return value; 
+               } catch (Exception e) {
+                       LOGGER.log(Level.WARNING, "Exception occured", e);
+                       transaction.rollback();
+                       throw e; 
+               } finally {
+                       em.close();
+               }
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizer.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizer.java
new file mode 100644 (file)
index 0000000..7930301
--- /dev/null
@@ -0,0 +1,22 @@
+package org.wamblee.support.persistence;
+
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+/**
+ * JPA customizer is used to customize properties for a given JPA implementation.
+ * 
+ * Implementations of JpaCustomizer are found using {@link ServiceLoader}. In case
+ * of testing with a specific JPA provider, the customizer library for that JPA provider
+ * must be on the classpath as well. 
+ * 
+ * @author Erik Brakkee
+ */
+public interface JpaCustomizer {
+
+    void customize(PersistenceUnitDescription aPersistenceUnit, Map<String,String> aJpaProperties);
+    
+    ITableFilterSimple getJpaTables();
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizerBuilder.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizerBuilder.java
new file mode 100644 (file)
index 0000000..a824bf6
--- /dev/null
@@ -0,0 +1,20 @@
+package org.wamblee.support.persistence;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ServiceLoader;
+
+public class JpaCustomizerBuilder {
+
+    private static final ServiceLoader<JpaCustomizer> CUSTOMIZERS = 
+        ServiceLoader.load(JpaCustomizer.class);
+    
+    
+    public static JpaCustomizer getCustomizer() { 
+        List<JpaCustomizer> customizers = new ArrayList<JpaCustomizer>(); 
+        for (JpaCustomizer customizer: CUSTOMIZERS) { 
+            customizers.add(customizer);
+        }
+        return new CompositeJpaCustomizer(customizers);
+    }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaTester.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaTester.java
new file mode 100644 (file)
index 0000000..a6a512f
--- /dev/null
@@ -0,0 +1,113 @@
+package org.wamblee.support.persistence;
+
+import javax.sql.DataSource;
+
+import org.dbunit.IDatabaseTester;
+
+/**
+ * This class is the entry point for JPA tests. Test code should construct a JpaTester in the 
+ * <code>@Before</code> method and call {@link #start()} on it in that method. Also, test code should 
+ * call {@link #stop()} on it in the <code>@After</code> method.  
+ * 
+ * This class is constructed with a description of the persistence unit to be tested. The principle is that
+ * an existing <code>persistence.xml</code> can be tested without change in unit test code. 
+ *  
+ * It then takes care of the following: 
+ * <ul> 
+ *   <li>  Creating an inmemory database for testing (default) or connecting to an external database. 
+ *        See {@link DatabaseBuilder} for more information on how a databse is obtained. 
+ *   </li>
+ *   <li> Drop all database tables that are related to the persistence unit under test, including JPA provider
+ *      specific tables. 
+ *   </li>
+ *   <li>  Creating a datasource for the database and make the datasource available through JNDI. 
+ *   </li>
+ *   <li> Creating the entity manager factory for JPA and configuring it in such a way that schema creation 
+ *      happens. (Typically, schema creation will be disabled in the persistence.xml but this utility enables it 
+ *      for unit test). 
+ *   </li>
+ *   <li> Creating a DBUnit database tester which is appropriately configured for the persistence unit under test. 
+ *   </li>
+ * </ul>
+ * 
+ * The main entry point for all this functionality is the {@link PersistenceUnitDescription} which describes the 
+ * persistence unit and must be provided at construction of the <code>JpaTester</code>
+ * 
+ * NOTE: Persistence XML files should be explicitly configured with the classes that are part of the persistence unit
+ * since scanning of classes does not work correctly in a unit test environment. This is currently the only limitation.
+ */
+public class JpaTester {
+
+       private PersistenceUnitDescription persistenceUnit;
+       private Database db;
+       private DataSource dataSource;
+       private DatabaseUtils dbUtils;
+       private JpaBuilder jpaBuilder;
+       private IDatabaseTester dbTester;
+
+       /**
+        * Constructs the tester.
+        * @param aPersistenceUnit Persistence unit under test. 
+        */
+       public JpaTester(PersistenceUnitDescription aPersistenceUnit) {
+               persistenceUnit = aPersistenceUnit;
+       }
+
+       /**
+        * Starts the tester. This must be called prior to running the test. 
+        * @throws Exception
+        */
+       public void start() throws Exception {
+               db = DatabaseBuilder.getDatabase();
+               dataSource = db.start();
+
+               dbUtils = new DatabaseUtils(dataSource, persistenceUnit.getTables());
+               dbUtils.dropTables();
+               dbUtils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables());
+
+               jpaBuilder = new JpaBuilder(dataSource, persistenceUnit);
+               jpaBuilder.start();
+
+               // db tester should be created after Jpa builder because jpa builder
+               // creates the
+               // tables that the tester looks at when it is initialized.
+               dbTester = dbUtils.createDbTester();
+       }
+
+       /**
+        * Stops the tester. This must be called after the test. 
+        */
+       public void stop() {
+               if (jpaBuilder != null) {
+                       jpaBuilder.stop();
+               }
+               if (db != null) {
+                       db.stop();
+               }
+       }
+
+       public Database getDb() {
+               return db;
+       }
+
+       public DataSource getDataSource() {
+               return dataSource;
+       }
+
+       public IDatabaseTester getDbTester() {
+               return dbTester;
+       }
+
+       public DatabaseUtils getDbUtils() {
+               return dbUtils;
+       }
+
+       public JpaBuilder getJpaBuilder() {
+               return jpaBuilder;
+       }
+
+       public PersistenceUnitDescription getPersistenceUnit() {
+               return persistenceUnit;
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/PersistenceUnitDescription.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/PersistenceUnitDescription.java
new file mode 100644 (file)
index 0000000..a2499b4
--- /dev/null
@@ -0,0 +1,28 @@
+package org.wamblee.support.persistence;
+
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+public class PersistenceUnitDescription {
+
+       private String jndiName; 
+       private String unitName; 
+       private ITableFilterSimple tables; 
+       
+       public PersistenceUnitDescription(String aJndiName, String aUnitName, ITableFilterSimple aTables) {
+               jndiName = aJndiName;
+               unitName = aUnitName;
+               tables = aTables; 
+       }
+       
+       public String getJndiName() {
+               return jndiName;
+       }
+       
+       public String getUnitName() {
+               return unitName;
+       }
+       
+       public ITableFilterSimple getTables() { 
+               return tables; 
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/package-info.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/java/org/wamblee/support/persistence/package-info.java
new file mode 100644 (file)
index 0000000..1bd7050
--- /dev/null
@@ -0,0 +1,23 @@
+/**
+ * This package provide a number of utilities for database testing and in particular with 
+ * JPA. 
+ * 
+ * The following utilities are available: 
+ * <ul>
+ *   <li> {@link JpaTester}: The main entry point for all JPA tests. 
+ *   </li>
+ *   <li> {@link JpaBuilder}: A utility constructed by <code>JpaTester</code> that provides a callback based 
+ *      style of working with transaction-scoped entity managers. 
+ *   </li>
+ *   <li> {@link DatabaseUtils}: A utility constructed by <code>JpaTester</code> for working with databases in general. Test code will not use this 
+ *        utility often. 
+ *   </li>
+ *   <li> {@link org.dbunit.IDatabaseTester}: A DB unit database tester. The test code can use this database tester. 
+ *   It is also created by <code>JpaTester</code>
+ *   </li>
+ *   <li> {@link DatabaseBuilder}: A utility by which test code can transparently create an inmemory database or 
+ *      connect to an external database. This is also used by <code>JpaTester</code>
+ *   </li>
+ * </ul>
+ */
+package org.wamblee.support.persistence;
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/main/resources/META-INF/services/org.wamblee.support.persistence.DatabaseProvider b/tags/wamblee-utils-0.2.1/test/enterprise/src/main/resources/META-INF/services/org.wamblee.support.persistence.DatabaseProvider
new file mode 100644 (file)
index 0000000..62979fb
--- /dev/null
@@ -0,0 +1,2 @@
+org.wamblee.support.persistence.DerbyDatabaseProvider
+org.wamblee.support.persistence.ExternalDatabaseProvider
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/jndi/StubInitiaContextFactoryTest.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/jndi/StubInitiaContextFactoryTest.java
new file mode 100644 (file)
index 0000000..6016e2b
--- /dev/null
@@ -0,0 +1,41 @@
+package org.wamblee.support.jndi;
+
+import static junit.framework.Assert.assertEquals;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.jndi.StubInitialContextFactory;
+
+public class StubInitiaContextFactoryTest {
+
+       @Before
+       @After
+       public void setUp() { 
+               StubInitialContextFactory.unregister();
+       }
+
+       
+       @Test(expected = NamingException.class)
+       public void testLookupNotRegistered() throws Exception { 
+               InitialContext ctx = new InitialContext();
+               ctx.bind("a/b", "hallo");
+       }
+       
+       @Test
+       public void testLookup() throws Exception {
+           StubInitialContextFactory.register();
+           
+               InitialContext ctx = new InitialContext();
+               ctx.bind("a/b", "hallo");
+               
+               ctx = new InitialContext(); 
+               Object obj = ctx.lookup("a/b");
+               
+               assertEquals("hallo", obj);
+       }
+       
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseBuilderTest.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseBuilderTest.java
new file mode 100644 (file)
index 0000000..5136487
--- /dev/null
@@ -0,0 +1,16 @@
+package org.wamblee.support.persistence;
+
+import org.junit.Test;
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.support.persistence.DatabaseDescription;
+
+public class DatabaseBuilderTest {
+
+       
+       @Test
+       public void testListAvailableDatabases() {
+               for (DatabaseDescription description: DatabaseBuilder.getSupportedDatabases()) { 
+                       System.out.println(description);
+               }
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseUtilsTestBase.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseUtilsTestBase.java
new file mode 100644 (file)
index 0000000..e55f134
--- /dev/null
@@ -0,0 +1,89 @@
+package org.wamblee.support.persistence;
+
+import static junit.framework.Assert.assertEquals;
+
+import javax.persistence.EntityManager;
+import javax.sql.DataSource;
+
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+public class DatabaseUtilsTestBase {
+    private Database db;
+    private DataSource dataSource;
+    private PersistenceUnitDescription persistenceUnit;
+    private JpaBuilder builder;
+    private DatabaseUtils dbutils;
+    private IDatabaseTester dbtester;
+
+    @Before
+    public void setUp() throws Exception {
+        db = DatabaseBuilder.getDatabase();
+        dataSource = db.start();
+
+        persistenceUnit = new MyPersistenceUnit();
+
+        dbutils = new DatabaseUtils(dataSource, persistenceUnit.getTables());
+        dbutils.dropTables();
+        dbutils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables());
+
+        builder = new JpaBuilder(dataSource, persistenceUnit);
+        builder.start();
+        
+        dbtester = dbutils.createDbTester();
+    }
+
+    @After
+    public void tearDown() {
+        builder.stop();
+        db.stop();
+    }
+
+    @Test
+    public void testTablesCorrect() throws Exception {
+        String[] tables = dbutils.getTableNames();
+        assertEquals(1, tables.length);
+        assertEquals("XYZ_MYENTITY", tables[0]);
+    }
+
+    @Test
+    public void testDeleteTables() throws Exception {
+        String[] tables = dbutils.getTableNames();
+        assertEquals(1, tables.length);
+        assertEquals("XYZ_MYENTITY", tables[0]);
+
+        // Put some data in the database.
+        builder.execute(new JpaUnitOfWork<Void>() {
+            public Void execute(EntityManager em) {
+                MyEntity entity = new MyEntity("a", "b");
+                em.persist(entity);
+                return null;
+            }
+        });
+
+        // Verify one row is written (using Db unit)
+        ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
+        assertEquals(1, table.getRowCount());
+
+        // Clean the database
+        dbutils.cleanDatabase();
+        table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
+        assertEquals(0, table.getRowCount());
+
+        // Now drop the database
+        dbutils.dropTables();
+        dbutils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables());
+        tables = dbutils.getTableNames();
+        assertEquals(0, tables.length);
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DerbyDatabaseTest.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/DerbyDatabaseTest.java
new file mode 100644 (file)
index 0000000..ffc17ae
--- /dev/null
@@ -0,0 +1,47 @@
+package org.wamblee.support.persistence;
+
+import java.sql.Connection;
+
+import javax.sql.DataSource;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DatabaseBuilder;
+
+
+public class DerbyDatabaseTest {
+
+       private Database db; 
+       private DataSource ds; 
+       
+       @Before
+       public void setUp() { 
+               db = DatabaseBuilder.getDatabase();
+               ds = db.start();
+       }
+       
+       @After
+       public void tearDown() { 
+               db.stop(); 
+       }
+       
+       @Test
+       public void testConnect() throws Exception { 
+               Connection conn = ds.getConnection();
+               try { 
+                       System.out.println("Database name: " + conn.getMetaData().getDatabaseProductName());  
+               } finally { 
+                       conn.close();
+               }
+       }
+       
+       @Test
+       public void testUseASecondTimeInTheSameTestCase() throws Exception { 
+               testConnect(); 
+               tearDown();
+               setUp();
+               testConnect();
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/ExternalDatabaseTest.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/ExternalDatabaseTest.java
new file mode 100644 (file)
index 0000000..dbe5800
--- /dev/null
@@ -0,0 +1,53 @@
+package org.wamblee.support.persistence;
+
+import java.sql.Connection;
+
+import javax.sql.DataSource;
+
+import org.junit.Test;
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.support.persistence.DatabaseProvider;
+import org.wamblee.support.persistence.ExternalDatabase;
+
+import static junit.framework.TestCase.*;
+
+public class ExternalDatabaseTest {
+
+       @Test
+       public void testExternalDB() throws Exception {
+               // Connect to inmemory db using External database class.
+
+               Database inmemory = DatabaseBuilder
+                               .getDatabase(DatabaseProvider.CAPABILITY_IN_MEMORY);
+               try {
+                       inmemory.start();
+
+                       System.setProperty(ExternalDatabase.DB_URL_PROP, inmemory
+                                       .getExternalJdbcUrl());
+                       System.setProperty(ExternalDatabase.DB_USER_PROP, inmemory
+                                       .getUsername());
+                       System.setProperty(ExternalDatabase.DB_PASSWORD_PROP, inmemory
+                                       .getPassword());
+
+                       Database external = DatabaseBuilder
+                                       .getDatabase(DatabaseProvider.CAPABILITY_EXTERNAL);
+                       assertTrue(external instanceof ExternalDatabase);
+                       try {
+                               DataSource ds = external.start();
+                               Connection conn = ds.getConnection();
+                               try {
+                                       System.out.println("Database name: "
+                                                       + conn.getMetaData().getDatabaseProductName());
+                               } finally {
+                                       conn.close();
+                               }
+                       } finally {
+                               external.stop();
+                       }
+               } finally {
+                       inmemory.stop();
+               }
+
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntity.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntity.java
new file mode 100644 (file)
index 0000000..c2b4728
--- /dev/null
@@ -0,0 +1,39 @@
+package org.wamblee.support.persistence;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "XYZ_MYENTITY")
+public class MyEntity {
+
+       @Id
+       @GeneratedValue(strategy = GenerationType.AUTO)
+       private Long id; 
+       
+       private String sleuteltje; 
+       private String value; 
+       
+       
+       public MyEntity() { 
+          // Empty     
+       }
+       
+       public MyEntity(String aKey, String aValue) { 
+               sleuteltje = aKey; 
+               value = aValue; 
+       }
+       
+       public String getKey() {
+               return sleuteltje;
+       }
+       
+       public String getValue() {
+               return value;
+       }
+
+       
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntityExampleTestBase.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntityExampleTestBase.java
new file mode 100644 (file)
index 0000000..77f6114
--- /dev/null
@@ -0,0 +1,87 @@
+package org.wamblee.support.persistence;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import javax.sql.DataSource;
+
+import org.dbunit.DataSourceDatabaseTester;
+import org.dbunit.DatabaseTestCase;
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaTester;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+import static junit.framework.Assert.*;
+
+
+/**
+ * This class shows an example of how to test an entity  using jpa. 
+ */
+public class MyEntityExampleTestBase {
+
+       // This is the magical object that does all the test setup. 
+    private JpaTester jpaTester; 
+    
+    // The jpa tester initializes a lot for us....
+    
+    // A JPA builder that provides a transaction scoped entity manager for us. 
+    private JpaBuilder builder; 
+    
+    // The database tester for dbunit which is appropriately configured for our persistence unit. 
+    private IDatabaseTester dbtester; 
+    
+    // Database utilities with some additional functionality for working with the databse
+    // such as dropping tables, cleaning tables, etc. 
+    private DatabaseUtils dbutils; 
+       
+       @Before
+       public void setUp() throws Exception {
+
+               // First we create the JpaTester by telling us which persistence unit we are going to test
+               jpaTester = new JpaTester(new MyPersistenceUnit());
+           jpaTester.start();
+           
+           // Retrieve some useful objects fromt he jpa tester. It also provides direct access to the datasource
+           // but we don't need it. We can use datbase utils if we want to execute straight JDBC calls. 
+           builder = jpaTester.getJpaBuilder();
+           dbtester = jpaTester.getDbTester();
+           dbutils = jpaTester.getDbUtils(); 
+       }
+       
+       @After
+       public void tearDown() { 
+               jpaTester.stop();
+       }
+       
+       @Test
+       public void testEntityPersistence() throws Exception { 
+               
+               // Use the JPA builder to create a transaction scoped entity manager for as and execute the 
+               // unit of work. 
+               builder.execute(new JpaUnitOfWork<Void>() {
+                       public Void execute(EntityManager em) {
+                               MyEntity entity = new MyEntity("a", "b"); 
+                               em.persist(entity);
+                               return null; 
+                       }
+               }); 
+               
+               // Verify one row is written (using Db unit)
+               ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY");
+               assertEquals(1, table.getRowCount());
+               
+           assertEquals("a", table.getValue(0, "SLEUTELTJE")); 
+           assertEquals("b", table.getValue(0, "VALUE"));
+               
+               // For this simple test, it can also be done through DatabaseUtils
+               assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY"));
+       
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyPersistenceUnit.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyPersistenceUnit.java
new file mode 100644 (file)
index 0000000..777dd88
--- /dev/null
@@ -0,0 +1,15 @@
+package org.wamblee.support.persistence;
+
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+/**
+ * This class describes the persistence unit that we are testing. 
+ */
+public class MyPersistenceUnit extends PersistenceUnitDescription {
+       private static final String JNDI_NAME = "wamblee/support/test";
+       private static final String PERSISTENCE_UNIT_NAME = "org.wamblee.jee.support-test";
+       
+       public MyPersistenceUnit() { 
+               super(JNDI_NAME, PERSISTENCE_UNIT_NAME, new MyTables());
+       }
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyTables.java b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/java/org/wamblee/support/persistence/MyTables.java
new file mode 100644 (file)
index 0000000..1283a8f
--- /dev/null
@@ -0,0 +1,25 @@
+package org.wamblee.support.persistence;
+
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+/**
+ * This class describes the tables we are testing. 
+ * This implementation selects all tables with the "XYZ" prefix. 
+ */
+public class MyTables implements ITableFilterSimple {
+               
+       /**
+        * 
+        * @param aJpaTables Specific tables used by the JPA provider in addition to those for the 
+        *   entities.  
+        */
+       public MyTables() { 
+               // Empty.
+       }
+
+       public boolean accept(String tableName) throws DataSetException {
+               return tableName.startsWith("XYZ_");
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/enterprise/src/test/resources/META-INF/persistence.xml b/tags/wamblee-utils-0.2.1/test/enterprise/src/test/resources/META-INF/persistence.xml
new file mode 100644 (file)
index 0000000..c252881
--- /dev/null
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<persistence version="1.0"
+       xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
+       <persistence-unit name="org.wamblee.jee.support-test"
+               transaction-type="JTA">
+               <jta-data-source>wamblee/support/test</jta-data-source>
+               <class>org.wamblee.support.persistence.MyEntity</class>
+               <properties>
+                       <!--
+                               <property name="toplink.ddl-generation"
+                               value="drop-and-create-tables" />
+                       -->
+                       <!--  <property name="toplink.ddl-generation" value="none" /> -->
+                       <property name="toplink.ddl-generation" value="create-tables" />
+
+                       <!--
+                               <property name="toplink.create-ddl-jdbc-file-name"
+                               value="create_tm_ddl.jdbc" />
+                       -->
+                       <!--
+                               <property name="toplink.drop-ddl-jdbc-file-name"
+                               value="drop_tm_ddl.jdbc" />
+                       -->
+
+                       <property name="toplink.logging.level" value="INFO" />
+
+                       <!--
+                               Toplink 2nd level cache disable for JSROuteRule, this is required so
+                               that changes made by one instance in a cluster become visible to the
+                               cluster. See
+                               http://www.oracle.com/technology/products/ias/toplink/JPA/essentials/toplink-jpa-extensions.html#TopLinkCaching
+                               for information on these toplink caching properties.
+                       -->
+                       <property name="toplink.cache.shared.default" value="false" />
+
+               </properties>
+
+       </persistence-unit>
+</persistence>
diff --git a/tags/wamblee-utils-0.2.1/test/hibernate/pom.xml b/tags/wamblee-utils-0.2.1/test/hibernate/pom.xml
new file mode 100644 (file)
index 0000000..f7bdfcd
--- /dev/null
@@ -0,0 +1,48 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-test-hibernate</artifactId>
+  <packaging>jar</packaging>
+  <name>/test/hibernate</name>
+  <url>http://wamblee.org</url>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+      <type>test-jar</type>
+    </dependency>
+
+    <dependency>
+      <groupId>org.dbunit</groupId>
+      <artifactId>dbunit</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>javax.persistence</groupId>
+      <artifactId>persistence-api</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-hibernate-jpa</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+
+  </dependencies>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java b/tags/wamblee-utils-0.2.1/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java
new file mode 100644 (file)
index 0000000..fa4def8
--- /dev/null
@@ -0,0 +1,31 @@
+package org.wamblee.support.persistence.hibernate;
+
+import java.util.Map;
+
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.wamblee.support.persistence.JpaCustomizer;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+public class HibernateJpaCustomizer implements JpaCustomizer {
+
+    public HibernateJpaCustomizer() { 
+        // Empty
+    }
+    
+    @Override
+    public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+        // Hibernate: Override transaction type and datasource
+        aJpaProperties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
+        aJpaProperties.put("javax.persistence.jtaDataSource", null);
+        aJpaProperties.put("javax.persistence.nonJtaDataSource", aPersistenceUnit.getJndiName());
+        
+        // Hibernate schema generation
+        aJpaProperties.put("hibernate.hbm2ddl.auto", "create");     
+    }
+    
+    @Override
+    public ITableFilterSimple getJpaTables() {
+        return new HibernateTables();
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java b/tags/wamblee-utils-0.2.1/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java
new file mode 100644 (file)
index 0000000..4b2c8a0
--- /dev/null
@@ -0,0 +1,20 @@
+package org.wamblee.support.persistence.hibernate;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+/**
+ * Toplink-specific tables. 
+ */
+public class HibernateTables implements ITableFilterSimple {
+
+       private static final List<String> TABLES = Arrays.asList(new String[] { "" } );
+       
+       public boolean accept(String aTableName) throws DataSetException {
+               return TABLES.contains(aTableName);
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/hibernate/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer b/tags/wamblee-utils-0.2.1/test/hibernate/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer
new file mode 100644 (file)
index 0000000..d057634
--- /dev/null
@@ -0,0 +1 @@
+org.wamblee.support.persistence.hibernate.HibernateJpaCustomizer
diff --git a/tags/wamblee-utils-0.2.1/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java b/tags/wamblee-utils-0.2.1/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java
new file mode 100644 (file)
index 0000000..68edf22
--- /dev/null
@@ -0,0 +1,23 @@
+package org.wamblee.support.persistence.hibernate;
+
+import static junit.framework.Assert.assertEquals;
+
+import javax.persistence.EntityManager;
+import javax.sql.DataSource;
+
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.DatabaseUtilsTestBase;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+public class DatabaseUtilsTest extends DatabaseUtilsTestBase {
+   // Empty, all tests inherited
+}
diff --git a/tags/wamblee-utils-0.2.1/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java b/tags/wamblee-utils-0.2.1/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java
new file mode 100644 (file)
index 0000000..537cb54
--- /dev/null
@@ -0,0 +1,29 @@
+package org.wamblee.support.persistence.hibernate;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import javax.sql.DataSource;
+
+import org.dbunit.DataSourceDatabaseTester;
+import org.dbunit.DatabaseTestCase;
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaTester;
+import org.wamblee.support.persistence.MyEntityExampleTestBase;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+import static junit.framework.Assert.*;
+
+
+/**
+ * This class shows an example of how to test an entity  using jpa. 
+ */
+public class MyEntityExampleTest extends MyEntityExampleTestBase {
+    // Empty, all tests are inherited
+}
diff --git a/tags/wamblee-utils-0.2.1/test/pom.xml b/tags/wamblee-utils-0.2.1/test/pom.xml
new file mode 100644 (file)
index 0000000..5672485
--- /dev/null
@@ -0,0 +1,36 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-test</artifactId>
+  <packaging>pom</packaging>
+  <name>/test</name>
+  <url>http://wamblee.org</url>
+
+  <modules>
+    <module>enterprise</module>
+    <module>hibernate</module>
+  </modules>
+
+  <profiles>
+    <profile>
+      <id>all</id>
+      <activation>
+        <property>
+          <name>!performRelease</name>
+        </property>
+      </activation>
+      <modules>
+        <module>eclipselink</module>
+        <module>toplink-essentials</module>
+      </modules>
+    </profile>
+  </profiles>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/pom.xml b/tags/wamblee-utils-0.2.1/test/toplink-essentials/pom.xml
new file mode 100644 (file)
index 0000000..3c97305
--- /dev/null
@@ -0,0 +1,58 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+  <parent>
+    <groupId>org.wamblee</groupId>
+    <artifactId>wamblee-utils</artifactId>
+    <version>0.2.1</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.wamblee</groupId>
+  <artifactId>wamblee-test-toplink-essentials</artifactId>
+  <packaging>jar</packaging>
+  <name>/test/toplinkessentials</name>
+  <url>http://wamblee.org</url>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+    </dependency>
+
+    <dependency>
+      <groupId>org.wamblee</groupId>
+      <artifactId>wamblee-test-enterprise</artifactId>
+      <version>0.2.1</version>
+      <type>test-jar</type>
+    </dependency>
+
+    <dependency>
+      <groupId>org.dbunit</groupId>
+      <artifactId>dbunit</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>javax.persistence</groupId>
+      <artifactId>persistence-api</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>toplink.essentials</groupId>
+      <artifactId>toplink-essentials</artifactId>
+    </dependency>
+
+
+  </dependencies>
+
+    <repositories>
+        <repository>
+            <id>javaee</id>
+            <name>Java EE repo at SUN</name>
+            <url>http://download.java.net/maven/1</url>
+            <layout>legacy</layout>
+        </repository>
+
+    </repositories>
+
+</project>
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java b/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java
new file mode 100644 (file)
index 0000000..814fe59
--- /dev/null
@@ -0,0 +1,59 @@
+package org.wamblee.support.persistence.toplink;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+
+import oracle.toplink.essentials.jndi.JNDIConnector;
+import oracle.toplink.essentials.sessions.DatabaseLogin;
+import oracle.toplink.essentials.sessions.Session;
+import oracle.toplink.essentials.threetier.ServerSession;
+import oracle.toplink.essentials.tools.sessionconfiguration.SessionCustomizer;
+/**
+ * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a
+ * JTA SE pu instead of a RESOURCE_LOCAL SE pu.
+ * 
+ * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE 
+ * environment together with our JNDI stub. 
+ */
+public class JndiSessionCustomizer
+    implements SessionCustomizer {
+       
+       public JndiSessionCustomizer() {
+               // Empty.
+       }
+  /**
+   * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP
+   */
+  public void customize(Session session) throws Exception {
+    JNDIConnector connector = null;
+    Context context = null;
+    try {
+      context = new InitialContext();
+      if(null != context) {
+        connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE
+        // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP
+        // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in
+        // the COMPOSITE_NAME_LOOKUP being set
+        // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set
+        connector.setLookupType(JNDIConnector.STRING_LOOKUP);
+        // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe
+        JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector();
+        writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+        JNDIConnector readConnector =
+            (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector();
+        readConnector.setLookupType(JNDIConnector.STRING_LOOKUP);
+        System.out.println("JndiSessionCustomizer: configured " + connector.getName());
+      }
+      else {
+        throw new Exception("JndiSessionCustomizer: Context is null");
+      }
+    }
+    catch(Exception e) {
+      e.printStackTrace();
+    }
+  }
+}
\ No newline at end of file
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java b/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java
new file mode 100644 (file)
index 0000000..5ba15e8
--- /dev/null
@@ -0,0 +1,30 @@
+package org.wamblee.support.persistence.toplink;
+
+import java.util.Map;
+
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.wamblee.support.persistence.JpaCustomizer;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+
+public class ToplinkJpaCustomizer implements JpaCustomizer {
+
+    public ToplinkJpaCustomizer() { 
+        // Empty
+    }
+    
+    @Override
+    public void customize(PersistenceUnitDescription aPersistenceUnit, Map<String, String> aJpaProperties) {
+        // Hack to make JNDI lookup of the datasource work with toplink
+        aJpaProperties.put("toplink.session.customizer", JndiSessionCustomizer.class
+                .getName());
+        
+        // DDL generation for toplink
+        aJpaProperties.put("toplink.ddl-generation", "create-tables");   
+    }
+    
+    @Override
+    public ITableFilterSimple getJpaTables() {
+        return new ToplinkTables();
+    }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java b/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java
new file mode 100644 (file)
index 0000000..cd3a056
--- /dev/null
@@ -0,0 +1,20 @@
+package org.wamblee.support.persistence.toplink;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.dbunit.dataset.DataSetException;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+
+/**
+ * Toplink-specific tables. 
+ */
+public class ToplinkTables implements ITableFilterSimple {
+
+       private static final List<String> TABLES = Arrays.asList(new String[] { "SEQUENCE" } );
+       
+       public boolean accept(String aTableName) throws DataSetException {
+               return TABLES.contains(aTableName);
+       }
+
+}
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer b/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer
new file mode 100644 (file)
index 0000000..82d1265
--- /dev/null
@@ -0,0 +1 @@
+org.wamblee.support.persistence.toplink.ToplinkJpaCustomizer
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java b/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java
new file mode 100644 (file)
index 0000000..095109d
--- /dev/null
@@ -0,0 +1,23 @@
+package org.wamblee.support.persistence.toplink;
+
+import static junit.framework.Assert.assertEquals;
+
+import javax.persistence.EntityManager;
+import javax.sql.DataSource;
+
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.Database;
+import org.wamblee.support.persistence.DatabaseBuilder;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.DatabaseUtilsTestBase;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.PersistenceUnitDescription;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+public class DatabaseUtilsTest extends DatabaseUtilsTestBase {
+   // Empty, all tests inherited
+}
diff --git a/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java b/tags/wamblee-utils-0.2.1/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java
new file mode 100644 (file)
index 0000000..415ee70
--- /dev/null
@@ -0,0 +1,29 @@
+package org.wamblee.support.persistence.toplink;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Persistence;
+import javax.sql.DataSource;
+
+import org.dbunit.DataSourceDatabaseTester;
+import org.dbunit.DatabaseTestCase;
+import org.dbunit.IDatabaseTester;
+import org.dbunit.dataset.ITable;
+import org.dbunit.dataset.filter.ITableFilterSimple;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.DatabaseUtils;
+import org.wamblee.support.persistence.JpaBuilder;
+import org.wamblee.support.persistence.JpaTester;
+import org.wamblee.support.persistence.MyEntityExampleTestBase;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+import static junit.framework.Assert.*;
+
+
+/**
+ * This class shows an example of how to test an entity  using jpa. 
+ */
+public class MyEntityExampleTest extends MyEntityExampleTestBase {
+    // Empty, all tests are inherited
+}