From ddd261f331280640c5b53c7128230b629ebcd268 Mon Sep 17 00:00:00 2001 From: Erik Brakkee Date: Fri, 16 Apr 2010 22:06:17 +0000 Subject: [PATCH] source code formatting. --- pom.xml | 27 +- .../security/authorization/AllOperation.java | 43 +- .../authorization/AnyUserCondition.java | 40 +- .../authorization/AuthorizationException.java | 58 +- .../AuthorizationInitializer.java | 34 +- .../authorization/AuthorizationResult.java | 20 +- .../authorization/AuthorizationRule.java | 40 +- .../authorization/AuthorizationService.java | 73 +- .../authorization/CreateOperation.java | 22 +- .../DefaultAuthorizationService.java | 193 +- .../DefaultOperationRegistry.java | 103 +- .../authorization/DeleteOperation.java | 21 +- .../authorization/GroupUserCondition.java | 58 +- .../authorization/IsaOperationCondition.java | 64 +- .../security/authorization/Operation.java | 17 +- .../authorization/OperationCondition.java | 22 +- .../authorization/OperationRegistry.java | 50 +- .../security/authorization/PathCondition.java | 21 +- .../security/authorization/ReadOperation.java | 23 +- .../authorization/RegexpPathCondition.java | 52 +- .../StartsWithPathCondition.java | 34 +- .../authorization/UrlAuthorizationRule.java | 275 +-- .../security/authorization/UserCondition.java | 20 +- .../authorization/WriteOperation.java | 24 +- .../hibernate/AuthorizationMappingFiles.java | 27 +- .../PersistentAuthorizationService.java | 126 +- .../encryption/Md5HexMessageDigester.java | 34 +- .../security/encryption/MessageDigester.java | 22 +- .../org/wamblee/usermgt/AbstractUserSet.java | 69 +- .../main/java/org/wamblee/usermgt/Group.java | 111 +- .../java/org/wamblee/usermgt/GroupSet.java | 75 +- .../org/wamblee/usermgt/InMemoryGroupSet.java | 88 +- .../org/wamblee/usermgt/InMemoryUserSet.java | 96 +- .../org/wamblee/usermgt/JaasUserAccessor.java | 77 +- .../org/wamblee/usermgt/NameValidator.java | 18 +- .../wamblee/usermgt/RegexpNameValidator.java | 66 +- .../main/java/org/wamblee/usermgt/User.java | 304 ++-- .../org/wamblee/usermgt/UserAccessor.java | 16 +- .../wamblee/usermgt/UserAdminInitializer.java | 65 +- .../wamblee/usermgt/UserAdministration.java | 215 ++- .../usermgt/UserAdministrationImpl.java | 220 ++- .../usermgt/UserGroupRepositoryComponent.java | 69 +- .../org/wamblee/usermgt/UserMgtException.java | 150 +- .../java/org/wamblee/usermgt/UserSet.java | 117 +- .../hibernate/AuthorizationComponent.java | 72 +- .../AuthorizationLightComponent.java | 54 +- .../usermgt/hibernate/HibernateGroupSet.java | 151 +- .../usermgt/hibernate/HibernateUserSet.java | 184 +- .../UserAdministrationComponent.java | 82 +- .../UserAdministrationLightComponent.java | 63 +- .../UsermgtHibernateMappingFiles.java | 35 +- .../AuthorizationServiceTest.java | 248 ++- .../DefaultOperationRegistryTest.java | 82 +- .../RegexpPathConditionTest.java | 28 +- .../StartsWithPathConditionTest.java | 15 +- .../authorization/TestAuthorizationRule.java | 100 +- .../security/authorization/TestResource.java | 37 +- .../authorization/TestUserAccessor.java | 54 +- .../UrlAuthorizationRuleTest.java | 104 +- .../PersistentAuthorizationServiceTest.java | 187 +- .../encryption/MessageDigesterTest.java | 21 +- .../wamblee/usermgt/InMemoryGroupSetTest.java | 241 +-- .../wamblee/usermgt/InMemoryUserSetTest.java | 458 +++-- .../usermgt/UserAdministrationImplTest.java | 381 ++-- .../org/wamblee/usermgt/UsermgtTestUtils.java | 125 +- .../hibernate/HibernateGroupSetTest.java | 176 +- .../HibernateUserAdministrationTest.java | 151 +- .../hibernate/HibernateUserSetTest.java | 201 ++- .../UserMgtRepositoryTestContainer.java | 38 +- .../main/java/org/wamblee/cache/Cache.java | 54 +- .../java/org/wamblee/cache/CachedObject.java | 91 +- .../main/java/org/wamblee/cache/EhCache.java | 72 +- .../java/org/wamblee/cache/ForeverCache.java | 52 +- .../java/org/wamblee/cache/ZeroCache.java | 59 +- .../wamblee/collections/CollectionFilter.java | 47 +- .../java/org/wamblee/concurrency/JvmLock.java | 31 +- .../java/org/wamblee/concurrency/Lock.java | 27 +- .../wamblee/concurrency/ReadWriteLock.java | 28 +- .../org/wamblee/conditions/AndCondition.java | 33 +- .../org/wamblee/conditions/Condition.java | 21 +- .../wamblee/conditions/FixedCondition.java | 39 +- .../org/wamblee/conditions/OrCondition.java | 33 +- .../conditions/PropertyRegexCondition.java | 70 +- .../java/org/wamblee/general/BeanFactory.java | 49 +- .../wamblee/general/BeanFactoryException.java | 29 +- .../java/org/wamblee/general/BeanKernel.java | 72 +- .../org/wamblee/general/ClassLoaderUtils.java | 55 +- .../main/java/org/wamblee/general/Pair.java | 23 +- .../org/wamblee/io/ClassPathResource.java | 33 +- .../java/org/wamblee/io/DirectoryMonitor.java | 185 +- .../java/org/wamblee/io/FileResource.java | 20 +- .../java/org/wamblee/io/InputResource.java | 17 +- .../java/org/wamblee/io/SimpleProcess.java | 316 ++-- .../java/org/wamblee/io/StreamResource.java | 20 +- .../observer/DefaultObserverNotifier.java | 19 +- .../java/org/wamblee/observer/Observable.java | 47 +- .../java/org/wamblee/observer/Observer.java | 19 +- .../wamblee/observer/ObserverNotifier.java | 23 +- .../persistence/AbstractPersistent.java | 79 +- .../org/wamblee/persistence/Persistent.java | 57 +- .../wamblee/reflection/ReflectionUtils.java | 146 +- .../org/wamblee/xml/ClasspathUriResolver.java | 36 +- .../main/java/org/wamblee/xml/DomUtils.java | 163 +- .../java/org/wamblee/xml/XMLException.java | 31 +- .../java/org/wamblee/xml/XslTransformer.java | 132 +- .../org/wamblee/cache/CachedObjectTest.java | 159 +- .../collections/CollectionFilterTest.java | 44 +- .../concurrency/AbstractLockTestCase.java | 55 +- .../org/wamblee/concurrency/JvmLockTest.java | 33 +- .../concurrency/ReadWriteLockTest.java | 85 +- .../wamblee/conditions/AndConditionTest.java | 51 +- .../conditions/GreaterThanCondition.java | 26 +- .../wamblee/conditions/LessThanCondition.java | 26 +- .../wamblee/conditions/OrConditionTest.java | 51 +- .../PropertyRegexConditionTest.java | 71 +- .../java/org/wamblee/conditions/TestBean.java | 31 +- .../org/wamblee/general/BeanKernelTest.java | 50 +- .../java/org/wamblee/general/PairTest.java | 21 +- .../org/wamblee/general/TestBeanFactory.java | 39 +- .../org/wamblee/io/ClassPathResourceTest.java | 17 +- .../org/wamblee/io/DirectoryMonitorTest.java | 201 ++- .../io/DirectoryMonitorTestProgram.java | 50 +- .../java/org/wamblee/io/FileResourceTest.java | 33 +- .../java/org/wamblee/io/FileSystemUtils.java | 691 ++++---- .../org/wamblee/io/StreamResourceTest.java | 27 +- .../test/java/org/wamblee/io/TestData.java | 320 ++-- .../java/org/wamblee/io/TestResource.java | 32 +- .../org/wamblee/observer/ObservableTest.java | 236 +-- .../java/org/wamblee/test/AssertionUtils.java | 105 +- .../java/org/wamblee/test/EventTracker.java | 62 +- .../java/org/wamblee/test/TimingUtils.java | 22 +- .../wamblee/xml/ClasspathUriResolverTest.java | 53 +- .../test/java/org/wamblee/xml/XmlUtils.java | 87 +- .../org/wamblee/xml/XslTransformerTest.java | 194 +- .../concurrency/spring/LockAdvice.java | 49 +- .../general/spring/SpringBeanFactory.java | 66 +- .../hibernate/HibernateMappingFiles.java | 28 +- .../hibernate/HibernateSupport.java | 246 +-- .../concurrency/spring/LockAdviceTest.java | 80 +- .../general/spring/SpringBeanFactoryTest.java | 39 +- .../general/spring/TestBeanFactory.java | 16 +- .../test/spring/HibernateExporter.java | 46 +- .../wamblee/test/spring/HibernateUpdater.java | 34 +- .../wamblee/test/spring/HibernateUtils.java | 75 +- .../test/spring/TestSpringBeanFactory.java | 64 +- .../test/spring/TestTransactionCallback.java | 17 +- .../TestTransactionCallbackWithoutResult.java | 15 +- .../wamblee/system/adapters/ClassAdapter.java | 82 +- .../system/adapters/ClassConfiguration.java | 160 +- .../adapters/ConstructorConfiguration.java | 349 ++-- .../system/adapters/DefaultContainer.java | 77 +- .../system/adapters/FixedValueProvider.java | 48 +- .../system/adapters/ObjectAdapter.java | 93 +- .../system/adapters/ObjectConfiguration.java | 79 +- .../system/adapters/ParameterValues.java | 236 +-- .../adapters/RequiredInterfaceProvider.java | 63 +- .../system/adapters/SetterConfiguration.java | 610 ++++--- .../system/adapters/ValueProvider.java | 19 +- .../system/components/PropertyComponent.java | 104 +- .../wamblee/system/container/Container.java | 437 +++-- .../system/core/AbstractComponent.java | 476 +++-- .../org/wamblee/system/core/Component.java | 138 +- .../system/core/DefaultProvidedInterface.java | 222 ++- .../system/core/DefaultRequiredInterface.java | 360 ++-- .../org/wamblee/system/core/DefaultScope.java | 278 ++- .../wamblee/system/core/NamedInterface.java | 18 +- .../system/core/ProvidedInterface.java | 42 +- .../core/ProvidedInterfaceImplementation.java | 78 +- .../system/core/RequiredInterface.java | 84 +- .../java/org/wamblee/system/core/Scope.java | 143 +- .../system/core/SystemAssemblyException.java | 39 +- .../system/graph/CompositeEdgeFilter.java | 54 +- .../org/wamblee/system/graph/DefaultEdge.java | 61 +- .../org/wamblee/system/graph/DefaultNode.java | 52 +- .../java/org/wamblee/system/graph/Edge.java | 21 +- .../org/wamblee/system/graph/EdgeFactory.java | 19 +- .../org/wamblee/system/graph/EdgeFilter.java | 24 +- .../wamblee/system/graph/EdgeSelector.java | 62 +- .../java/org/wamblee/system/graph/Graph.java | 172 +- .../java/org/wamblee/system/graph/Node.java | 15 +- .../org/wamblee/system/graph/Visitor.java | 21 +- .../CheckExternallyProvidedVisitor.java | 79 +- .../CheckExternallyRequiredVisitor.java | 59 +- ...ckRequiredProvidedMultiplicityVisitor.java | 91 +- .../CheckStartupDependenciesVisitor.java | 60 +- .../graph/component/ComponentGraph.java | 158 +- .../system/graph/component/ComponentNode.java | 42 +- ...ConnectExternalProvidedProvidedFilter.java | 91 +- ...tRequiredExternallyRequiredEdgeFilter.java | 94 +- .../ConnectRequiredProvidedEdgeFilter.java | 90 +- .../ExternalProvidedInterfaceNode.java | 70 +- .../ExternalRequiredInterfaceNode.java | 66 +- .../system/graph/component/LinkVisitor.java | 49 +- .../component/ProvidedInterfaceNode.java | 65 +- .../component/RequiredInterfaceNode.java | 66 +- .../RequiredProvidedEdgeFactory.java | 65 +- .../system/graph/component/package-info.java | 1 - .../wamblee/system/graph/package-info.java | 3 +- .../system/adapters/AdapterTestCase.java | 46 +- .../system/adapters/ClassAdapterTest.java | 107 +- .../adapters/ClassConfigurationTest.java | 64 +- .../ConstructorConfigurationTest.java | 277 +-- .../system/adapters/DefaultContainerTest.java | 74 +- .../system/adapters/ObjectAdapterTest.java | 77 +- .../adapters/SetterConfigurationTest.java | 711 ++++---- .../java/org/wamblee/system/adapters/X1.java | 36 +- .../java/org/wamblee/system/adapters/X10.java | 69 +- .../java/org/wamblee/system/adapters/X11.java | 33 +- .../java/org/wamblee/system/adapters/X2.java | 38 +- .../java/org/wamblee/system/adapters/X3.java | 36 +- .../java/org/wamblee/system/adapters/X4.java | 46 +- .../java/org/wamblee/system/adapters/X5.java | 100 +- .../java/org/wamblee/system/adapters/X6.java | 72 +- .../java/org/wamblee/system/adapters/X7.java | 88 +- .../java/org/wamblee/system/adapters/X8.java | 72 +- .../java/org/wamblee/system/adapters/X9.java | 48 +- .../system/components/DatabaseComponent.java | 75 +- .../components/DatabaseComponentFactory.java | 26 +- .../wamblee/system/container/Application.java | 133 +- .../system/container/ContainerTest.java | 1561 +++++++++-------- .../system/core/AbstractComponentTest.java | 97 +- .../core/DefaultInterfaceDescriptorTest.java | 185 +- .../core/DefaultRequiredInterfaceTest.java | 22 +- .../wamblee/system/core/DefaultScopeTest.java | 66 +- .../org/wamblee/system/core/Environment.java | 202 ++- .../wamblee/system/core/IntegerComponent.java | 164 +- .../core/RequiredInterfaceComparator.java | 26 +- .../wamblee/system/core/StringComponent.java | 177 +- .../system/graph/CompositeEdgeFilterTest.java | 131 +- .../org/wamblee/system/graph/GraphTest.java | 187 +- .../wamblee/system/graph/MyEdgeFactory.java | 41 +- .../java/org/wamblee/system/graph/MyNode.java | 35 +- ...xternalProvidedProvidedEdgeFilterTest.java | 119 +- ...uiredExternallyRequiredEdgeFilterTest.java | 88 +- ...ConnectRequiredProvidedEdgeFilterTest.java | 169 +- .../system/spring/ConfiguredProperties.java | 30 +- .../wamblee/system/spring/PropertySetter.java | 59 +- .../system/spring/RequiredServiceBean.java | 103 +- .../system/spring/SpringComponent.java | 423 +++-- .../wamblee/system/spring/StringResource.java | 151 +- .../spring/component/DatasourceComponent.java | 99 +- .../spring/component/HibernateComponent.java | 170 +- .../org/wamblee/system/spring/BlaService.java | 63 +- .../spring/ConfiguredPropertiesTest.java | 39 +- .../wamblee/system/spring/HelloService.java | 48 +- .../wamblee/system/spring/HelloService2.java | 31 +- .../system/spring/SpringComponentTest.java | 215 ++- .../system/spring/SubSpringComponent.java | 50 +- .../system/spring/SubSpringComponent2.java | 54 +- .../component/DatabaseTesterComponent.java | 396 +++-- .../eclipselink/EclipselinkJpaCustomizer.java | 49 +- .../eclipselink/EclipselinkTables.java | 35 +- .../eclipselink/JndiSessionCustomizer.java | 112 +- .../eclipselink/DatabaseUtilsTest.java | 25 +- .../eclipselink/MyEntityExampleTest.java | 20 +- .../persistence/DerbyDatabaseProvider.java | 63 +- .../hibernate/HibernateJpaCustomizer.java | 48 +- .../hibernate/HibernateTables.java | 33 +- .../hibernate/DatabaseUtilsTest.java | 25 +- .../hibernate/MyEntityExampleTest.java | 20 +- .../toplink/JndiSessionCustomizer.java | 112 +- .../toplink/ToplinkJpaCustomizer.java | 49 +- .../persistence/toplink/ToplinkTables.java | 35 +- .../toplink/DatabaseUtilsTest.java | 25 +- .../toplink/MyEntityExampleTest.java | 20 +- 265 files changed, 16397 insertions(+), 10050 deletions(-) diff --git a/pom.xml b/pom.xml index 428eb2a8..ebcb6e76 100644 --- a/pom.xml +++ b/pom.xml @@ -328,9 +328,7 @@ 2.0.0 compile - - - + @@ -345,6 +343,19 @@ javadoc:jar deploy + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.5 + + + org.wamblee + wamblee-code-style + 1.0-SNAPSHOT + + + + maven-clean-plugin 2.4 @@ -374,6 +385,13 @@ UNIX org.wamblee.jalopy.xml + + + org.wamblee + wamblee-code-style + 1.0-SNAPSHOT + + org.apache.maven.plugins @@ -491,8 +509,9 @@ org.apache.maven.plugins maven-checkstyle-plugin + 2.5 - config/sun_checks.xml + org.wamblee.checkstyle.xml diff --git a/security/src/main/java/org/wamblee/security/authorization/AllOperation.java b/security/src/main/java/org/wamblee/security/authorization/AllOperation.java index f5b5a7f1..02b1f1e1 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AllOperation.java +++ b/security/src/main/java/org/wamblee/security/authorization/AllOperation.java @@ -1,55 +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.security.authorization; /** - * An superclass of all other operations. + * An superclass of all other operations. */ public class AllOperation implements Operation { - + /** + * DOCUMENT ME! + */ private static final String OPERATION = "all"; - + /** - * Operation name. + * Operation name. */ private String name; - - /** + +/** * Constructs an all operation. * */ - public AllOperation() { - name = 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; + protected AllOperation(String aName) { + name = aName; } /* (non-Javadoc) * @see org.wamblee.security.authorization.Operation#getName() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public String getName() { - return name; + return name; } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java b/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java index fdee026e..26a9153e 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java @@ -1,52 +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.security.authorization; import org.wamblee.persistence.AbstractPersistent; + import org.wamblee.usermgt.User; + /** - * Matches any user. + * Matches any user. * * @author Erik Brakkee */ -public class AnyUserCondition extends AbstractPersistent implements UserCondition { - - /** +public class AnyUserCondition extends AbstractPersistent + implements UserCondition { +/** * Constructs the condition. * */ - public AnyUserCondition() { + public AnyUserCondition() { // Empty. } /* (non-Javadoc) * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean matches(User aUser) { - return true; + return true; } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { - return "AnyUserCondition()"; + return "AnyUserCondition()"; } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java b/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java index a9c930db..1821ed64 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java +++ b/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java @@ -1,44 +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.security.authorization; /** - * Authorization exception to be thrown when - * a resouce may not be accessed. + * 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; + /** + * DOCUMENT ME! + */ + private Object resource; + /** + * DOCUMENT ME! + */ + private Operation operation; + +/** + * Creates a new AuthorizationException object. + * + * @param aResource DOCUMENT ME! + * @param aOperation DOCUMENT ME! + */ public AuthorizationException(Object aResource, Operation aOperation) { - super("Operation '" + aOperation + "' not allowed on '" + aResource + "'"); - resource = aResource; - operation = aOperation; + super("Operation '" + aOperation + "' not allowed on '" + aResource + + "'"); + resource = aResource; + operation = aOperation; } - - public Object getResource() { - return resource; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Object getResource() { + return resource; } - - public Operation getOperation() { + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Operation getOperation() { return operation; } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java b/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java index 7423eab9..642dd337 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java +++ b/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java @@ -1,43 +1,45 @@ /* * 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. + * Inititializer class for authorization rules. This class initializes the + * authorization rules in case none are present. */ public class AuthorizationInitializer { - + /** + * DOCUMENT ME! + */ 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); - } - } + 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/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java b/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java index a394910f..1756bde4 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java +++ b/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java @@ -1,19 +1,18 @@ /* * 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; /** @@ -22,23 +21,20 @@ package org.wamblee.security.authorization; * @author Erik Brakkee */ public enum AuthorizationResult { - /** +/** * Access is granted. */ GRANTED, - - /** +/** * Access is denied. */ DENIED, - - /** +/** * Access is undecided. */ UNDECIDED, - - /** +/** * Unsupported resource. */ - UNSUPPORTED_RESOURCE + UNSUPPORTED_RESOURCE; } diff --git a/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java b/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java index 575f4f21..9f0efca9 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java +++ b/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java @@ -1,46 +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.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. + * 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. + * 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); + AuthorizationResult isAllowed(Object aResource, Operation anOperation, + User aUser); } diff --git a/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java b/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java index 01150622..feb7053c 100644 --- a/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java +++ b/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java @@ -1,69 +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.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. + * 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 - * RuntimeException in case access is not allowed. - * @param aResource Resource to check. - * @param aOperation Operation to perform. - * @return Resource that was checked. + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aResource DOCUMENT ME! + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! */ - T check(T aResource, Operation aOperation); - + T check(T aResource, Operation aOperation); + /** - * Gets the authorization rules. - * @return Rules. + * Gets the authorization rules. + * + * @return Rules. */ - AuthorizationRule[] getRules(); - + AuthorizationRule[] getRules(); + /** - * Appends a new authorization rule to the end. - * @param aRule Rule to append. + * Appends a new authorization rule to the end. + * + * @param aRule Rule to append. */ - void appendRule(AuthorizationRule aRule); - + void appendRule(AuthorizationRule aRule); + /** - * Removes a rule. - * @param aRule Index of the rule to remove. + * Removes a rule. + * + * @param aIndex Index of the rule to remove. */ - void removeRule(int aIndex); - + void removeRule(int aIndex); + /** - * Inserts a rule. - * @param aIndex Index of the position of the rule after insertion. - * @param aRule Rule to insert. + * 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/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java b/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java index b9a96d8e..a43f079d 100644 --- a/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java +++ b/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java @@ -1,36 +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. + * Represents an operation to create something. * * @author Erik Brakkee */ public class CreateOperation extends AllOperation { - - private static final String OPERATION = "create"; - /** + * DOCUMENT ME! + */ + private static final String OPERATION = "create"; + +/** * Constructs the operation. * */ - public CreateOperation() { + public CreateOperation() { super(OPERATION); } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java b/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java index 1d6499e0..e52ced7e 100644 --- a/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java +++ b/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java @@ -1,155 +1,216 @@ /* * 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; +import java.util.ArrayList; +import java.util.List; + + /** - * 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. + * 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 { - +public class DefaultAuthorizationService extends AbstractPersistent + implements AuthorizationService { /** - * List of ordered authorization rules. + * List of ordered authorization rules. */ - private List rules; - + private List rules; + /** - * User accessor used to obtain the current user. + * User accessor used to obtain the current user. */ - private UserAccessor userAccessor; - + private UserAccessor userAccessor; + /** - * Name for this instance of the authorization service. + * 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(); - userAccessor = aAccessor; - name = aName; + rules = new ArrayList(); + userAccessor = aAccessor; + name = aName; } - - /** + +/** * Constructs the authorization service. */ public DefaultAuthorizationService() { - rules = new ArrayList(); - userAccessor = null; - name = null; + rules = new ArrayList(); + userAccessor = null; + name = null; } - + /** - * Sets the user accessor. - * @param aUserAccessor User accessor. + * Sets the user accessor. + * + * @param aUserAccessor User accessor. */ - public void setUserAccessor(UserAccessor aUserAccessor) { - userAccessor = aUserAccessor; + public void setUserAccessor(UserAccessor aUserAccessor) { + userAccessor = aUserAccessor; } /* (non-Javadoc) * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation) */ + /** + * DOCUMENT ME! + * + * @param aResource DOCUMENT ME! + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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; } + User user = userAccessor.getCurrentUser(); + + for (AuthorizationRule rule : rules) { + switch (rule.isAllowed(aResource, aOperation, user)) { + case DENIED: + return false; + + case GRANTED: + return true; } } - return false; + + return false; } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation) */ + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aResource DOCUMENT ME! + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws AuthorizationException DOCUMENT ME! + */ public T check(T aResource, Operation aOperation) { - if ( !isAllowed(aResource, aOperation)) { + if (!isAllowed(aResource, aOperation)) { throw new AuthorizationException(aResource, aOperation); } + return aResource; } - - protected String getName() { - return name; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected String getName() { + return name; } - - public void setName(String aName) { - name = aName; + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + */ + public void setName(String aName) { + name = aName; } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.AuthorizationService#getRules() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public AuthorizationRule[] getRules() { - return rules.toArray(new AuthorizationRule[0]); + return rules.toArray(new AuthorizationRule[0]); } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule) */ + /** + * DOCUMENT ME! + * + * @param aRule DOCUMENT ME! + */ public void appendRule(AuthorizationRule aRule) { - rules.add(aRule); + rules.add(aRule); } /* (non-Javadoc) * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, org.wamblee.security.authorization.AuthorizationRule) */ + /** + * DOCUMENT ME! + * + * @param aIndex DOCUMENT ME! + * @param aRule DOCUMENT ME! + */ public void insertRuleAfter(int aIndex, AuthorizationRule aRule) { - rules.add(aIndex, aRule); + rules.add(aIndex, aRule); } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int) */ + /** + * DOCUMENT ME! + * + * @param aIndex DOCUMENT ME! + */ public void removeRule(int aIndex) { - rules.remove(aIndex); + rules.remove(aIndex); } - + /** - * For OR mapping. - * @return The rules. + * For OR mapping. + * + * @return The rules. */ protected List getMappedRules() { - return rules; + return rules; } - + /** * For OR mapping. - * @param aRules The rules. + * + * @param aRules The rules. */ - protected void setMappedRules(List aRules) { - rules = aRules; + protected void setMappedRules(List aRules) { + rules = aRules; } } diff --git a/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java b/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java index 472b2dac..ad34465d 100644 --- a/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java +++ b/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java @@ -1,88 +1,135 @@ /* * 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. + * 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 { + /** + * DOCUMENT ME! + */ + private Map operations; - private Map operations; - - public DefaultOperationRegistry(Operation[] aOperations) { +/** + * Creates a new DefaultOperationRegistry object. + * + * @param aOperations DOCUMENT ME! + */ + public DefaultOperationRegistry(Operation[] aOperations) { operations = new TreeMap(); - for (Operation operation: aOperations) { + + for (Operation operation : aOperations) { operations.put(operation.getName(), operation); } } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.OperationRegistry#getOperations(java.lang.Class) */ + /** + * DOCUMENT ME! + * + * @param aResourceClass DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Operation[] getOperations(Class aResourceClass) { - return operations.values().toArray(new Operation[0]); + return operations.values().toArray(new Operation[0]); } /* (non-Javadoc) * @see org.wamblee.security.authorization.OperationRegistry#encode(org.wamblee.security.authorization.Operation[]) */ + /** + * DOCUMENT ME! + * + * @param aOperations DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public String encode(Operation[] aOperations) { - StringBuffer buffer = new StringBuffer(); - for (Operation operation: aOperations) { - if ( buffer.length() > 0 ) { + 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) */ + /** + * DOCUMENT ME! + * + * @param aResourceClass DOCUMENT ME! + * @param aOperationsString DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Operation[] decode(Class aResourceClass, String aOperationsString) { - return decode(aOperationsString); + return decode(aOperationsString); } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aOperationsString DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IllegalArgumentException DOCUMENT ME! + */ public Operation[] decode(String aOperationsString) { - if ( aOperationsString.length() == 0 ) { - return new Operation[0]; + if (aOperationsString.length() == 0) { + return new Operation[0]; } - String[] names = aOperationsString.split(","); - ArrayList result = new ArrayList(); - for (String name: names) { + + String[] names = aOperationsString.split(","); + ArrayList result = new ArrayList(); + + for (String name : names) { Operation operation = operations.get(name); - if ( operation == null ) { - throw new IllegalArgumentException("Unknown operation '" + name + "'"); + + if (operation == null) { + throw new IllegalArgumentException("Unknown operation '" + name + + "'"); } + result.add(operation); } - return result.toArray(new Operation[0]); - } + return result.toArray(new Operation[0]); + } } diff --git a/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java b/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java index 7bdaac51..a910eea8 100644 --- a/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java +++ b/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java @@ -1,35 +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; /** - * Deletes the operation. + * Deletes the operation. * * @author Erik Brakkee */ public class DeleteOperation extends AllOperation { - - private static final String OPERATION = "delete"; - /** + * DOCUMENT ME! + */ + private static final String OPERATION = "delete"; + +/** * Constructs the operation. * */ - public DeleteOperation() { + public DeleteOperation() { super(OPERATION); } } diff --git a/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java b/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java index c0e91896..6bfe9269 100644 --- a/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java @@ -1,60 +1,70 @@ /* * 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. + * Checks if a user against a specific group. * * @author Erik Brakkee */ -public class GroupUserCondition extends AbstractPersistent implements UserCondition { - +public class GroupUserCondition extends AbstractPersistent + implements UserCondition { /** - * Group the user must be in. + * Group the user must be in. */ - private String group; - - /** + private String group; + +/** * Constructs the condition. * @param aGroup Group the user must be in. */ public GroupUserCondition(String aGroup) { - group = aGroup; + group = aGroup; } - - /** + +/** * For OR mapping. * */ - protected GroupUserCondition() { - group = null; + 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); + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean matches(User aUser) { + return aUser.isInGroup(group); } /** + * DOCUMENT ME! + * * @return Returns the group. */ protected String getGroup() { @@ -62,7 +72,9 @@ public class GroupUserCondition extends AbstractPersistent implements UserCondit } /** - * @param group The group to set. + * DOCUMENT ME! + * + * @param aGroup The group to set. */ protected void setGroup(String aGroup) { group = aGroup; @@ -71,9 +83,13 @@ public class GroupUserCondition extends AbstractPersistent implements UserCondit /* (non-Javadoc) * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return "GroupUserCondition(group=" + group + ")"; } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java b/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java index b738b5dd..dc984ff5 100644 --- a/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java @@ -1,45 +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; import org.wamblee.persistence.AbstractPersistent; + /** * Determiens if an operation is a subclass of a specified operation. */ -public class IsaOperationCondition extends AbstractPersistent implements - OperationCondition { - +public class IsaOperationCondition extends AbstractPersistent + implements OperationCondition { /** * Operation that the other operation must be a subclass of. */ - private Class operation; + private Class operation; - /** +/** * Constructs the condition. * * @param aOperation * Operation that an operation must be an instance of. */ - public IsaOperationCondition(Class aOperation) { + public IsaOperationCondition(Class aOperation) { operation = aOperation; } - /** +/** * For OR mapping. * */ @@ -49,50 +48,65 @@ public class IsaOperationCondition extends AbstractPersistent implements /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.OperationCondition#matches(org.wamblee.security.authorization.Operation) */ + /** + * DOCUMENT ME! + * + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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 null; } - return operation.getName(); + + return operation.getName(); } /** * Sets the operation as a string. For OR mapping only. - * - * @param aOperation - * Operation string. + * + * @param aOperation Operation string. + * + * @throws IllegalArgumentException DOCUMENT ME! */ protected void setOperationString(String aOperation) { - if (aOperation == null ) { + if (aOperation == null) { return; } - try { - operation = (Class)Class.forName(aOperation); - } catch (Exception e) { - throw new IllegalArgumentException("Unknown class '" + aOperation + "'"); + + try { + operation = (Class) Class.forName(aOperation); + } catch (Exception e) { + throw new IllegalArgumentException("Unknown class '" + aOperation + + "'"); } } /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return "IsaOperationCondition(operation=" + operation.getName() + ")"; } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/Operation.java b/security/src/main/java/org/wamblee/security/authorization/Operation.java index 24205065..54f99c6a 100644 --- a/security/src/main/java/org/wamblee/security/authorization/Operation.java +++ b/security/src/main/java/org/wamblee/security/authorization/Operation.java @@ -1,19 +1,18 @@ /* * 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; /** @@ -24,10 +23,10 @@ package org.wamblee.security.authorization; * @author Erik Brakkee */ public interface Operation { - /** - * Gets the name of the operation. - * @return Operation. + * Gets the name of the operation. + * + * @return Operation. */ - String getName(); + String getName(); } diff --git a/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java b/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java index db6e0d0a..be2a03c6 100644 --- a/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java @@ -1,35 +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. + * Determines if the operation matches. + * + * @param aOperation Operation. + * + * @return True iff the operation matches. */ - boolean matches(Operation aOperation); + boolean matches(Operation aOperation); } diff --git a/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java b/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java index bcce7c96..076e18cf 100644 --- a/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java +++ b/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java @@ -1,22 +1,20 @@ /* * 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. @@ -24,34 +22,42 @@ package org.wamblee.security.authorization; * @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. + * 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. + * 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. + * + * @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. + * + * @param aOperationsString Operations string as returned by {@link + * #encode(Operation[])}. + * + * @return Operations array. */ Operation[] decode(String aOperationsString); - } diff --git a/security/src/main/java/org/wamblee/security/authorization/PathCondition.java b/security/src/main/java/org/wamblee/security/authorization/PathCondition.java index 8c970177..603bbc45 100644 --- a/security/src/main/java/org/wamblee/security/authorization/PathCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/PathCondition.java @@ -1,34 +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 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. + * Checks if the path matches the condition. + * + * @param aPath Path to match. + * + * @return True iff the path matches. */ - boolean matches(String aPath); + boolean matches(String aPath); } diff --git a/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java b/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java index 839fdb18..5f9e4d5c 100644 --- a/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java +++ b/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java @@ -1,35 +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 read operation on a resource. + * Represents a read operation on a resource. * * @author Erik Brakkee */ public class ReadOperation extends AllOperation { - - private static final String OPERATION = "read"; - /** + * DOCUMENT ME! + */ + private static final String OPERATION = "read"; + +/** * Constructs the operation. * */ - public ReadOperation() { - super(OPERATION); + public ReadOperation() { + super(OPERATION); } } diff --git a/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java b/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java index 2cde6808..9b3a1c60 100644 --- a/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java @@ -1,59 +1,68 @@ /* * 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 { - +public class RegexpPathCondition extends AbstractPersistent + implements PathCondition { /** - * String the path must start with. + * String the path must start with. */ - private String pattern; - - /** + private String pattern; + +/** * Constructs the condition. * @param aPattern String the path must start with. */ - public RegexpPathCondition(String aPattern) { - pattern = aPattern; + public RegexpPathCondition(String aPattern) { + pattern = aPattern; } - - /** + +/** * For OR mapping. * */ - protected RegexpPathCondition() { - pattern = null; + protected RegexpPathCondition() { + pattern = null; } /* (non-Javadoc) * @see org.wamblee.security.authorization.PathCondition#matches(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aPath DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean matches(String aPath) { return aPath.matches(pattern); } /** + * DOCUMENT ME! + * * @return Returns the _path. */ protected String getPattern() { @@ -61,15 +70,22 @@ public class RegexpPathCondition extends AbstractPersistent implements PathCondi } /** + * DOCUMENT ME! + * * @param aPattern The _path to set. */ protected void setPattern(String aPattern) { pattern = aPattern; } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return "RegexpCondition(pattern = '" + pattern + "')"; diff --git a/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java b/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java index 59f8627c..090214c8 100644 --- a/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java @@ -1,48 +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. + * 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 + ".*"); + public StartsWithPathCondition(String aPath) { + super(aPath + ".*"); } - - /** + +/** * For OR mapping. * */ - protected StartsWithPathCondition() { - super(); + protected StartsWithPathCondition() { + super(); } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return "StartsWithPathCondition(pattern = '" + getPattern() + "')"; diff --git a/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java b/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java index a3184968..b3103fb1 100644 --- a/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java +++ b/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java @@ -1,83 +1,84 @@ /* * 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; + +import org.wamblee.persistence.AbstractPersistent; 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 - *
    - *
  • 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}. - *
  • - *
  • The user identity with which the resource is accessed. - * Whether a user is appropriate is determined by - * a {@link org.wamblee.security.authorization.UserCondition}. - *
  • - *
  • The operation that is requested. - * Whether the operation is appropriate is determined by a - * {@link org.wamblee.security.authorization.OperationCondition}. - *
  • - *
- * - * 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. + * Utility base class for implementation of authentication rules based on + * the + *
    + *
  • 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}.
  • + *
  • The user identity with which the resource is accessed. + * Whether a user is appropriate is determined by a {@link + * org.wamblee.security.authorization.UserCondition}.
  • + *
  • The operation that is requested. Whether the operation is + * appropriate is determined by a {@link + * org.wamblee.security.authorization.OperationCondition}.
  • + *
+ * 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 { - +public abstract class UrlAuthorizationRule extends AbstractPersistent + implements AuthorizationRule { + /** + * DOCUMENT ME! + */ private static final Logger LOGGER = Logger.getLogger(UrlAuthorizationRule.class); /** - * Result that the rule will return in case there is a match. + * 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. + * A condition which specifies which users the rule is for. */ - private UserCondition userCondition; + private UserCondition userCondition; /** - * Path the rule applies for. + * Path the rule applies for. */ private PathCondition pathCondition; /** - * Resource class that the rule applies for. + * Resource class that the rule applies for. */ private Class resourceClass; - + /** - * Operation that this rule is for. + * Operation that this rule is for. */ - private OperationCondition operationCondition; + 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. @@ -86,141 +87,191 @@ public abstract class UrlAuthorizationRule extends AbstractPersistent implements * @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); + 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; + + 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; + 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; + protected UrlAuthorizationRule() { + result = null; + userCondition = null; + pathCondition = null; + resourceClass = null; + operationCondition = null; } - /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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; + /** + * DOCUMENT ME! + * + * @param aResource DOCUMENT ME! + * @param anOperation DOCUMENT ME! + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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); + + 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, + * 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) ) { + protected AuthorizationResult isAllowed(String aPath, Operation aOperation, + User aUser) { + if (!pathCondition.matches(aPath)) { return UNDECIDED; } - if ( !operationCondition.matches(aOperation) ) { - return UNDECIDED; + + if (!operationCondition.matches(aOperation)) { + return UNDECIDED; } - if ( !userCondition.matches(aUser)) { + + if (!userCondition.matches(aUser)) { return UNDECIDED; } - return result; + + return result; } /** - * Gets the path of the resource. - * @param aResource Resource, guaranteed to be an instance of - * {@link #resourceClass}. - * @return Path of the resource. + * 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() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { - return "UrlAUthorizationRule(result = " + result + - ", pathCondition = " + pathCondition + - ", userCondition = " + userCondition + - ", resourceClass = " + resourceClass + ")"; + return "UrlAUthorizationRule(result = " + result + ", pathCondition = " + + pathCondition + ", userCondition = " + userCondition + + ", resourceClass = " + resourceClass + ")"; } - + /** - * Gets the authorization result for OR mapping. - * @return Result. + * Gets the authorization result for OR mapping. + * + * @return Result. */ protected String getAuthorizationResultString() { - if ( result == null ) { - return null; + if (result == null) { + return null; } - return result.toString(); + + return result.toString(); } - + /** - * Sets the authorization result, for OR mapping. - * @param aResult Result. + * Sets the authorization result, for OR mapping. + * + * @param aResult Result. */ protected void setAuthorizationResultString(String aResult) { result = AuthorizationResult.valueOf(aResult); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ protected String getResourceClassName() { - if ( resourceClass == null ) { + if (resourceClass == null) { return ""; } - return resourceClass.getName(); + + return resourceClass.getName(); } - - protected void setResourceClassName(String aResourceClass) { + + /** + * DOCUMENT ME! + * + * @param aResourceClass DOCUMENT ME! + * + * @throws IllegalArgumentException DOCUMENT ME! + */ + 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); + LOGGER.error("Cannot find resource class '" + aResourceClass + "'", + e); + throw new IllegalArgumentException(e.getMessage(), e); } } /** + * DOCUMENT ME! + * * @return Returns the operationCondition. */ public OperationCondition getOperationCondition() { @@ -228,6 +279,8 @@ public abstract class UrlAuthorizationRule extends AbstractPersistent implements } /** + * DOCUMENT ME! + * * @param aOperationCondition The operationCondition to set. */ protected void setOperationCondition(OperationCondition aOperationCondition) { @@ -235,6 +288,8 @@ public abstract class UrlAuthorizationRule extends AbstractPersistent implements } /** + * DOCUMENT ME! + * * @return Returns the pathCondition. */ public PathCondition getPathCondition() { @@ -242,6 +297,8 @@ public abstract class UrlAuthorizationRule extends AbstractPersistent implements } /** + * DOCUMENT ME! + * * @param aPathCondition The pathCondition to set. */ protected void setPathCondition(PathCondition aPathCondition) { @@ -249,6 +306,8 @@ public abstract class UrlAuthorizationRule extends AbstractPersistent implements } /** + * DOCUMENT ME! + * * @return Returns the userCondition. */ public UserCondition getUserCondition() { @@ -256,6 +315,8 @@ public abstract class UrlAuthorizationRule extends AbstractPersistent implements } /** + * DOCUMENT ME! + * * @param aUserCondition The userCondition to set. */ protected void setUserCondition(UserCondition aUserCondition) { diff --git a/security/src/main/java/org/wamblee/security/authorization/UserCondition.java b/security/src/main/java/org/wamblee/security/authorization/UserCondition.java index ad398770..a19fcd77 100644 --- a/security/src/main/java/org/wamblee/security/authorization/UserCondition.java +++ b/security/src/main/java/org/wamblee/security/authorization/UserCondition.java @@ -1,35 +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 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. + * 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/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java b/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java index 212ce316..67784ca8 100644 --- a/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java +++ b/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java @@ -1,36 +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. + * Represents a write operation on a resource. * * @author Erik Brakkee */ public class WriteOperation extends AllOperation { - - private static final String OPERATION = "write"; - /** + * DOCUMENT ME! + */ + private static final String OPERATION = "write"; + +/** * Constructs the operation. * */ - public WriteOperation() { - super(OPERATION); + public WriteOperation() { + super(OPERATION); } - } diff --git a/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java b/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java index 6bd87f6c..cae2f5fe 100644 --- a/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java +++ b/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java @@ -1,33 +1,38 @@ /* * 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. + * 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" }); +/** + * Creates a new AuthorizationMappingFiles object. + */ + 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/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java b/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java index 895e77e6..caf69903 100644 --- a/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java +++ b/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java @@ -1,42 +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.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; +import java.util.List; + + /** - * 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. + * 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 { - + implements AuthorizationService { /** * Name of query to find the service by name. */ @@ -61,23 +63,23 @@ public class PersistentAuthorizationService extends AbstractPersistent * User accessor. */ private UserAccessor userAccessor; - + /** - * Name of the service. + * Name of the service. */ - private String name; + private String name; /** - * Refresh interval in milliseconds. + * Refresh interval in milliseconds. */ private final long refreshInterval; - + /** - * Last refresh time. + * Last refresh time. */ - private long lastRefreshTime; + private long lastRefreshTime; - /** +/** * Constructs the persistent service. * * @param aName @@ -91,28 +93,29 @@ public class PersistentAuthorizationService extends AbstractPersistent * 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; + HibernateTemplate aTemplate, UserAccessor aAccessor, + long aRefreshInterval) { + template = aTemplate; + refreshInterval = aRefreshInterval; + lastRefreshTime = System.currentTimeMillis(); + userAccessor = aAccessor; + name = aName; } /** - * Initialize service if needed. + * Initialize service if needed. + * + * @throws IllegalArgumentException DOCUMENT ME! */ private void initialize() { if (service == null) { List result = template - .findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM, - name); + .findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM, name); if (result.size() > 1) { throw new IllegalArgumentException( - "Returned more than one service for name '" + name - + "' (" + result.size() + ")"); + "Returned more than one service for name '" + name + "' (" + + result.size() + ")"); } if (result.size() == 0) { @@ -127,41 +130,71 @@ public class PersistentAuthorizationService extends AbstractPersistent /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, * org.wamblee.security.authorization.Operation) */ + /** + * DOCUMENT ME! + * + * @param aResource DOCUMENT ME! + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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) */ + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aResource DOCUMENT ME! + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public T check(T aResource, Operation aOperation) { initialize(); refresh(); + return service.check(aResource, aOperation); } /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.AuthorizationService#getRules() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public AuthorizationRule[] getRules() { initialize(); refresh(); + return service.getRules(); } /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule) */ + /** + * DOCUMENT ME! + * + * @param aRule DOCUMENT ME! + */ public void appendRule(AuthorizationRule aRule) { initialize(); refresh(); @@ -171,9 +204,14 @@ public class PersistentAuthorizationService extends AbstractPersistent /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int) */ + /** + * DOCUMENT ME! + * + * @param aIndex DOCUMENT ME! + */ public void removeRule(int aIndex) { initialize(); refresh(); @@ -183,10 +221,16 @@ public class PersistentAuthorizationService extends AbstractPersistent /* * (non-Javadoc) - * + * * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, * org.wamblee.security.authorization.AuthorizationRule) */ + /** + * DOCUMENT ME! + * + * @param aIndex DOCUMENT ME! + * @param aRule DOCUMENT ME! + */ public void insertRuleAfter(int aIndex, AuthorizationRule aRule) { initialize(); refresh(); @@ -196,13 +240,13 @@ public class PersistentAuthorizationService extends AbstractPersistent /** * Refreshes the state of the service through hibernate. - * */ private synchronized void refresh() { - long time = System.currentTimeMillis(); - if ( time - lastRefreshTime > refreshInterval ) { + long time = System.currentTimeMillis(); + + if ((time - lastRefreshTime) > refreshInterval) { template.refresh(service); - lastRefreshTime = time; + lastRefreshTime = time; } } diff --git a/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java b/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java index 161b652e..a10112a9 100644 --- a/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java +++ b/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java @@ -1,34 +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.encryption; +import org.apache.commons.codec.binary.Hex; + import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import org.apache.commons.codec.binary.Hex; /** - * MD5 Hex encoder. + * MD5 Hex encoder. * * @author Erik Brakkee */ public class Md5HexMessageDigester implements MessageDigester { - - /** +/** * Constructs the message digester. * */ @@ -38,18 +37,27 @@ public class Md5HexMessageDigester implements MessageDigester { /* * (non-Javadoc) - * + * * @see org.wamblee.security.MessageDigester#hash(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aValue DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IllegalArgumentException DOCUMENT ME! + */ public String hash(String aValue) { try { - MessageDigest digest = MessageDigest.getInstance("MD5"); - byte[] result = digest.digest(aValue.getBytes()); - char[] charResult = Hex.encodeHex(result); + 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/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java b/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java index 685a4c79..aa68c3d8 100644 --- a/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java +++ b/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java @@ -1,31 +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. + * 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); - + String hash(String aValue); } diff --git a/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java b/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java index b000d687..784f7f10 100644 --- a/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java +++ b/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java @@ -1,52 +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.usermgt; -import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER; - import org.wamblee.security.encryption.MessageDigester; +import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER; /** - * User set base class. + * User set base class. */ public abstract class AbstractUserSet implements UserSet { - /** - * Password validator. + * Password validator. */ - private NameValidator passwordValidator; - + private NameValidator passwordValidator; + /** - * Password encoder. + * Password encoder. */ - private MessageDigester passwordEncoder; + private MessageDigester passwordEncoder; - - protected AbstractUserSet(NameValidator aPasswordValidator, - MessageDigester aPasswordEncoder) { - passwordValidator = aPasswordValidator; - passwordEncoder = aPasswordEncoder; +/** + * Creates a new AbstractUserSet object. + * + * @param aPasswordValidator DOCUMENT ME! + * @param aPasswordEncoder DOCUMENT ME! + */ + protected AbstractUserSet(NameValidator aPasswordValidator, + MessageDigester aPasswordEncoder) { + passwordValidator = aPasswordValidator; + passwordEncoder = aPasswordEncoder; } - + /** - * Sets the password validtor and encoder in the user. - * @param aUser User. + * Sets the password validtor and encoder in the user. + * + * @param aUser User. */ - protected void setPasswordInfo(User aUser) { + protected void setPasswordInfo(User aUser) { aUser.setPasswordValidator(passwordValidator); aUser.setPasswordEncoder(passwordEncoder); } @@ -54,12 +57,28 @@ public abstract class AbstractUserSet implements UserSet { /* (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); + /** + * DOCUMENT ME! + * + * @param aUsername DOCUMENT ME! + * @param aPassword DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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/security/src/main/java/org/wamblee/usermgt/Group.java b/security/src/main/java/org/wamblee/usermgt/Group.java index a8535417..9c7e9893 100644 --- a/security/src/main/java/org/wamblee/usermgt/Group.java +++ b/security/src/main/java/org/wamblee/usermgt/Group.java @@ -1,101 +1,136 @@ /* * 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.persistence.AbstractPersistent; + import java.io.Serializable; -import org.wamblee.persistence.AbstractPersistent; /** - * Represents a group. + * Represents a group. * * @author Erik Brakkee */ -public class Group extends AbstractPersistent implements Serializable, Comparable { - +public class Group extends AbstractPersistent implements Serializable, + Comparable { /** - * Group name. + * Group name. */ - private String name; + private String name; - /** +/** * Constructs the group. * @param aName */ Group(String aName) { super(); - name = aName; + name = aName; } - - public Group(Group aGroup) { - super(aGroup); + +/** + * Creates a new Group object. + * + * @param aGroup DOCUMENT ME! + */ + public Group(Group aGroup) { + super(aGroup); name = aGroup.name; } - - protected Group() { - super(); - name = null; + +/** + * Creates a new Group object. + */ + protected Group() { + super(); + name = null; } - + /** - * Gets the name of the group. - * @return Group name. + * Gets the name of the group. + * + * @return Group name. */ - public String getName() { - return name; + public String getName() { + return name; } - + /** - * Sets the group name. - * @param aName Group name. + * Sets the group name. + * + * @param aName Group name. */ void setName(String aName) { - name = aName; + name = aName; } - + /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean equals(Object aGroup) { - if ( !( aGroup instanceof Group )) { - return false; + if (!(aGroup instanceof Group)) { + return false; } - return name.equals(((Group)aGroup).name); + + return name.equals(((Group) aGroup).name); } - + /* (non-Javadoc) * @see java.lang.Object#hashCode() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public int hashCode() { - return name.hashCode(); + return name.hashCode(); } - + /* (non-Javadoc) * @see java.lang.Comparable#compareTo(T) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int compareTo(Object aGroup) { - return name.compareTo(((Group)aGroup).name); + return name.compareTo(((Group) aGroup).name); } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return "Group(pk = " + getPrimaryKey() + ", name=" + name + ")"; diff --git a/security/src/main/java/org/wamblee/usermgt/GroupSet.java b/security/src/main/java/org/wamblee/usermgt/GroupSet.java index 780d60bb..33beb43a 100644 --- a/security/src/main/java/org/wamblee/usermgt/GroupSet.java +++ b/security/src/main/java/org/wamblee/usermgt/GroupSet.java @@ -1,23 +1,23 @@ /* * 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. @@ -25,49 +25,72 @@ import java.util.Set; * @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. + * Must be called when the group has been modified to notify the + * group set. + * + * @param aGroup Group that was modified. */ - void groupModified(Group aGroup); - + void groupModified(Group aGroup); + /** - * Finds the group by name. - * @param aName Group name. - * @return Group or null if not found. + * 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. + * 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. + * Adds a group. If the group already exists, the existing group + * set is left unchanged. + * * @param aGroup Group. + * + * @return DOCUMENT ME! */ boolean add(Group aGroup); - + /** - * Removes a group. If the group does not exist, this method is a no-op. + * 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. + * + * @return True if the group was removed, false otherwise. */ boolean remove(Group aGroup); - + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Returns the current groups. * @return Groups. */ Set list(); /** - * @return The number of groups. + * DOCUMENT ME! + * + * @return The number of groups. */ - int size(); + int size(); } diff --git a/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java b/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java index b9d133ab..e5cafb0e 100644 --- a/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java +++ b/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java @@ -1,66 +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 java.util.Set; import java.util.TreeSet; + /** - * In-memory group set implementation. + * In-memory group set implementation. * * @author Erik Brakkee */ public class InMemoryGroupSet implements GroupSet { - /** - * Groups. + * Groups. */ - private Set groups; - - /** + private Set groups; + +/** * Constructs an empty group set. */ - public InMemoryGroupSet() { + public InMemoryGroupSet() { groups = new TreeSet(); } - + /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + */ public void groupModified(Group aGroup) { - groups.remove(aGroup); + groups.remove(aGroup); groups.add(aGroup); } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#find(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Group find(String aName) { - for (Group group: groups) { - if ( group.getName().equals(aName)) { + for (Group group : groups) { + if (group.getName().equals(aName)) { return new Group(group); } } - return null; + + return null; } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean contains(Group aGroup) { return groups.contains(aGroup); } @@ -68,6 +87,13 @@ public class InMemoryGroupSet implements GroupSet { /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean add(Group aGroup) { return groups.add(aGroup); } @@ -75,6 +101,13 @@ public class InMemoryGroupSet implements GroupSet { /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean remove(Group aGroup) { return groups.remove(aGroup); } @@ -82,19 +115,30 @@ public class InMemoryGroupSet implements GroupSet { /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#list() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set list() { - Set list = new TreeSet(); - for (Group group: groups) { + Set list = new TreeSet(); + + for (Group group : groups) { list.add(new Group(group)); } + return list; } - + /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#size() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int size() { - return groups.size(); + return groups.size(); } - } diff --git a/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java b/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java index 380d92c9..035dc993 100644 --- a/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java +++ b/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java @@ -1,25 +1,25 @@ /* * 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.MessageDigester; + import java.util.Set; import java.util.TreeSet; -import org.wamblee.security.encryption.MessageDigester; /** * In-memory user set. @@ -27,106 +27,162 @@ import org.wamblee.security.encryption.MessageDigester; * @author Erik Brakkee */ public class InMemoryUserSet extends AbstractUserSet { - /** - * Users. All users in this set have their password validator and encoder set. + * Users. All users in this set have their password validator and + * encoder set. */ private Set users; - /** +/** * Constructs an empty user set. */ - public InMemoryUserSet(NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) { + public InMemoryUserSet(NameValidator aPasswordValidator, + MessageDigester aPasswordEncoder) { super(aPasswordValidator, aPasswordEncoder); users = new TreeSet(); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + */ public void userModified(User aUser) { users.remove(aUser); - setPasswordInfo(aUser); + setPasswordInfo(aUser); users.add(aUser); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#find(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean add(User aUser) { setPasswordInfo(aUser); + return users.add(aUser); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean contains(User aUser) { return users.contains(aUser); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean remove(User aUser) { return users.remove(aUser); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#list() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set list() { Set list = new TreeSet(); + for (User user : users) { list.add(new User(user)); } + return list; } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#list(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set list(Group aGroup) { Set result = new TreeSet(); + for (User user : users) { if (user.getGroups().contains(aGroup)) { result.add(new User(user)); } } + return result; } - + /* (non-Javadoc) * @see org.wamblee.usermgt.UserSet#size() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int size() { - return users.size(); + return users.size(); } - } diff --git a/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java b/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java index 8102b82f..aefe447a 100644 --- a/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java +++ b/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java @@ -1,57 +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.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. + * Implementation of the user accessor that retrieves user information from + * JAAS. * * @author Erik Brakkee */ public class JaasUserAccessor implements UserAccessor { - /** - * User administration to use. + * User administration to use. */ private UserAdministration admin; /** - * Class of the JAAS user principal. + * 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()); + + 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); @@ -60,42 +63,58 @@ public class JaasUserAccessor implements UserAccessor { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAccessor#getCurrentUser() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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. + * 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 principals = subject.getPrincipals(); - Principal userPrincipal = null; - for ( Principal principal: principals) { - if ( principal.getClass().equals(userPrincipalClass)) { - if ( userPrincipal != null ) { + Set 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); + "Multiple principals for class '" + userPrincipalClass + + "', subject: " + subject); } - userPrincipal = principal; + + userPrincipal = principal; } } - if ( userPrincipal == null ) { + + if (userPrincipal == null) { throw new IllegalArgumentException( - "No user principal found for class '" + userPrincipalClass + "', subject: " + subject); + "No user principal found for class '" + userPrincipalClass + + "', subject: " + subject); } + return userPrincipal; } - } diff --git a/security/src/main/java/org/wamblee/usermgt/NameValidator.java b/security/src/main/java/org/wamblee/usermgt/NameValidator.java index f120d24a..2ad0db19 100644 --- a/security/src/main/java/org/wamblee/usermgt/NameValidator.java +++ b/security/src/main/java/org/wamblee/usermgt/NameValidator.java @@ -1,19 +1,18 @@ /* * 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; /** @@ -22,11 +21,12 @@ package org.wamblee.usermgt; * @author Erik Brakkee */ public interface NameValidator { - /** - * Validates a name. + * Validates a name. + * * @param aName Name - * @throws UserMgtException In case the name is invalid. + * + * @throws UserMgtException In case the name is invalid. */ - void validate(String aName) throws UserMgtException; + void validate(String aName) throws UserMgtException; } diff --git a/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java b/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java index 9d1421b4..40f9e669 100644 --- a/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java +++ b/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java @@ -1,85 +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.usermgt; import org.wamblee.usermgt.UserMgtException.Reason; + /** - * Validation of names based on a regular expression. + * Validation of names based on a regular expression. * * @author Erik Brakkee */ public class RegexpNameValidator implements NameValidator { - /** - * Convenience pattern for an id. + * 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. + * Convenience pattern for a password consisting of at least 6 + * characters. */ public static final String PASSWORD_PATTERN = ".{6}.*"; - + /** - * Pattern to use. + * Pattern to use. */ private String pattern; - + /** - * Reason to use when validation fails. + * Reason to use when validation fails. */ - private Reason reason; - + private Reason reason; + /** - * Message to report. + * Message to report. */ - private String message; - - /** + 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; + 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) { + 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) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public void validate(String aName) throws UserMgtException { - if ( !aName.matches(pattern)) { - throw new UserMgtException(reason, message); + if (!aName.matches(pattern)) { + throw new UserMgtException(reason, message); } } - } diff --git a/security/src/main/java/org/wamblee/usermgt/User.java b/security/src/main/java/org/wamblee/usermgt/User.java index 0a69cef9..53e95537 100644 --- a/security/src/main/java/org/wamblee/usermgt/User.java +++ b/security/src/main/java/org/wamblee/usermgt/User.java @@ -1,174 +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; +import org.wamblee.persistence.AbstractPersistent; + +import org.wamblee.security.encryption.MessageDigester; + +import org.wamblee.usermgt.UserMgtException.Reason; + 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. + * 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 { - +public class User extends AbstractPersistent implements Serializable, + Comparable { /** - * User name. + * User name. */ private String name; /** - * Password. + * Password. */ private String password; /** - * Groups the user belongs to. + * Groups the user belongs to. */ private Set groups; - + /** - * Password validator. + * Password validator. */ - private NameValidator passwordValidator; + private NameValidator passwordValidator; /** - * Password encoder. + * 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(); + 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(); + password = aPasswordEncoder.hash(aPassword); + groups = new TreeSet(); groups.add(aGroup); - passwordValidator = aPasswordValidator; - passwordEncoder = aPasswordEncoder; + passwordValidator = aPasswordValidator; + passwordEncoder = aPasswordEncoder; } - - public User(User aUser) { - super(aUser); - name = aUser.name; - password = aUser.password; - groups = new TreeSet(); - for (Group group: aUser.groups) { - groups.add(new Group(group)); + +/** + * Creates a new User object. + * + * @param aUser DOCUMENT ME! + */ + public User(User aUser) { + super(aUser); + name = aUser.name; + password = aUser.password; + groups = new TreeSet(); + + for (Group group : aUser.groups) { + groups.add(new Group(group)); } - passwordValidator = aUser.passwordValidator; - passwordEncoder = aUser.passwordEncoder; + + passwordValidator = aUser.passwordValidator; + passwordEncoder = aUser.passwordEncoder; } - - User() { - super(); - name = null; - password = null; - groups = null; - passwordValidator = null; - passwordEncoder = null; + +/** + * Creates a new User object. + */ + User() { + super(); + name = null; + password = null; + groups = null; + passwordValidator = null; + passwordEncoder = null; } - + /** - * Sets the password validator. - * @param aPasswordValidator Validator. + * Sets the password validator. + * + * @param aPasswordValidator Validator. */ - public void setPasswordValidator(NameValidator aPasswordValidator) { + public void setPasswordValidator(NameValidator aPasswordValidator) { passwordValidator = aPasswordValidator; } - + /** - * Sets the password encoder. - * @param aPasswordEncoder Encoder. + * Sets the password encoder. + * + * @param aPasswordEncoder Encoder. */ - public void setPasswordEncoder(MessageDigester aPasswordEncoder) { - passwordEncoder = aPasswordEncoder; + public void setPasswordEncoder(MessageDigester aPasswordEncoder) { + passwordEncoder = aPasswordEncoder; } /** + * DOCUMENT ME! + * * @return Returns the password. */ String getPassword() { return password; } - + /** - * Checks the password. - * @param aPassword Password to check. - * @throws UserMgtException In case the password is incorrect. + * 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) ) { + + 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. + * 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 { + public void changePassword(String aOldPassword, String aNewPassword) + throws UserMgtException { checkPassword(aOldPassword); passwordValidator.validate(aNewPassword); setPassword(aNewPassword); } /** - * @param aPassword - * The password to set. + * DOCUMENT ME! + * + * @param aPassword The password to set. + * + * @throws UserMgtException DOCUMENT ME! */ public void setPassword(String aPassword) throws UserMgtException { passwordValidator.validate(aPassword); password = passwordEncoder.hash(aPassword); } - + /** - * For OR mapping. - * @return Password. + * For OR mapping. + * + * @return Password. */ - protected String getPasswordString() { + protected String getPasswordString() { return password; } - + /** - * For OR mapping. - * @param aPassword Password. + * For OR mapping. + * + * @param aPassword Password. */ - protected void setPasswordString(String aPassword) { - password = aPassword; + protected void setPasswordString(String aPassword) { + password = aPassword; } /** + * DOCUMENT ME! + * * @return Returns the _user. */ public String getName() { @@ -176,51 +206,69 @@ public class User extends AbstractPersistent implements Serializable, Comparable } /** - * @param aName - * The username to set. + * DOCUMENT ME! + * + * @param aName The username to set. */ void setName(String aName) { name = aName; } /** - * Gets the groups the user belongs to. + * Gets the groups the user belongs to. + * * @return Groups. */ public Set getGroups() { - Set result = new TreeSet(); + Set result = new TreeSet(); result.addAll(groups); - return result; + + return result; } - + /** - * Checks whether the user belongs to the given group. - * @param aGroup Group. + * 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. + * 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)); } - + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Gets the group set. For OR mapping. * @return set of groups. */ - Set getGroupSet() { + Set getGroupSet() { return groups; } /** - * Sets the groups the user belongs to, for OR mapping. + * Sets the groups the user belongs to, for OR mapping. + * * @param aGroups Groups. */ void setGroupSet(Set aGroups) { @@ -228,68 +276,104 @@ public class User extends AbstractPersistent implements Serializable, Comparable } /** - * Adds the user to a group. + * 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. + * + * @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. + * 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); + + 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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean equals(Object aUser) { - if ( !(aUser instanceof User)) { - return false; + if (!(aUser instanceof User)) { + return false; } - User user = (User)aUser; + + User user = (User) aUser; + return name.equals(user.name); } - + /* (non-Javadoc) * @see java.lang.Object#hashCode() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public int hashCode() { - return name.hashCode(); + return name.hashCode(); } - + /* (non-Javadoc) * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { String result = "User(name=" + name + ", password=" + password; - for (Group group: groups) { - result += ", group=" + group; + + for (Group group : groups) { + result += (", group=" + group); } - return result + ")"; + + return result + ")"; } - + /* (non-Javadoc) * @see java.lang.Comparable#compareTo(T) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int compareTo(Object aUser) { - return name.compareTo(((User)aUser).name); + return name.compareTo(((User) aUser).name); } } diff --git a/security/src/main/java/org/wamblee/usermgt/UserAccessor.java b/security/src/main/java/org/wamblee/usermgt/UserAccessor.java index d3dd8a9e..577d5756 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserAccessor.java +++ b/security/src/main/java/org/wamblee/usermgt/UserAccessor.java @@ -1,19 +1,18 @@ /* * 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; /** @@ -23,8 +22,9 @@ package org.wamblee.usermgt; */ public interface UserAccessor { /** - * Gets the current user. - * @return Currently logged in user or null if no user is found. + * Gets the current user. + * + * @return Currently logged in user or null if no user is found. */ - User getCurrentUser(); + User getCurrentUser(); } diff --git a/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java b/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java index 58263ebc..2897d5e6 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java +++ b/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java @@ -1,80 +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.apache.log4j.Logger; + 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. + * 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); - /** + * DOCUMENT ME! + */ + 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) { + 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); - + "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. + * 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 { + String[] aGroups, String[] aPasswords) throws UserMgtException { for (int i = 0; i < aUsers.length; i++) { - String user = aUsers[i]; - String group = aGroups[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; - + assert groupObj != null; + LOGGER.info("Creating user: " + user + " password: " + password); aAdmin.createUser(user, password, groupObj); } diff --git a/security/src/main/java/org/wamblee/usermgt/UserAdministration.java b/security/src/main/java/org/wamblee/usermgt/UserAdministration.java index 1ce6fbfa..554590fd 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserAdministration.java +++ b/security/src/main/java/org/wamblee/usermgt/UserAdministration.java @@ -1,151 +1,216 @@ /* * 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 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. + * Creates a new group. + * + * @param aName Group name. + * * @return Group - * @throws UserMgtException In case there is a conflict with an existing group. + * + * @throws UserMgtException In case there is a conflict with an existing + * group. */ Group createGroup(String aName) throws UserMgtException; - - /** - * @return Number of users. + + /** + * DOCUMENT ME! + * + * @return Number of users. */ - int getUserCount(); - + int getUserCount(); + /** - * @return Number of groups. + * DOCUMENT ME! + * + * @return Number of groups. */ - int getGroupCount(); - + int getGroupCount(); + /** - * Must be called when the user is modified. + * 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. + * Must be called when the group is modified. + * + * @param aGroup Group. */ - void groupModified(Group aGroup); + void groupModified(Group aGroup); /** - * Gets the user for a given name. - * @param aName User name. - * @return User or null if not found. + * Gets the user for a given name. + * + * @param aName User name. + * + * @return User or null if not found. */ - User getUser(String aName); - + User getUser(String aName); + /** - * Gets the group for a given group name. - * @param aName Group name. - * @return Group or null if not found. + * Gets the group for a given group name. + * + * @param aName Group name. + * + * @return Group or null if not found. */ - Group getGroup(String aName); - + Group getGroup(String aName); + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Get the users. * @return All known users. */ - Set getUsers(); - + Set getUsers(); + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Gets the users for a given group. * @param aGroup Group. * @return Set of users (always non-null). */ Set getUsers(Group aGroup); - + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Gets all known groups. * @return Groups. */ Set 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. + * 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. + * 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. + * 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. + * 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. + * 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. + * 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. + * + * @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; + void removeUserFromGroup(User aUser, Group aGroup) + throws UserMgtException; } - diff --git a/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java b/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java index 55793da6..071791b2 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java +++ b/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java @@ -1,19 +1,18 @@ /* * 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; @@ -25,13 +24,13 @@ 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. */ @@ -41,126 +40,200 @@ public class UserAdministrationImpl implements UserAdministration { * All known groups. */ private GroupSet groups; - + /** - * Validator for user names. + * Validator for user names. */ private NameValidator userValidator; - + /** - * Validator for group names. + * 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; + 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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aPassword DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public User createUser(String aUser, String aPassword, Group aGroup) - throws UserMgtException { + 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) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ 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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + */ public void userModified(User aUser) { users.userModified(aUser); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + */ public void groupModified(Group aGroup) { groups.groupModified(aGroup); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#getUser(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public User getUser(String aName) { return users.find(aName); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#getGroup(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Group getGroup(String aName) { return groups.find(aName); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#getUsers() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set getUsers() { return users.list(); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set getUsers(Group aGroup) { return users.list(aGroup); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#getGroups() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set getGroups() { return groups.list(); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#removeUser(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public void removeUser(User aUser) throws UserMgtException { checkUser(aUser); users.remove(aUser); @@ -168,32 +241,52 @@ public class UserAdministrationImpl implements UserAdministration { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#removeGroup(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ 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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aUserName DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public void renameUser(User aUser, String aUserName) - throws UserMgtException { + 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. @@ -204,19 +297,30 @@ public class UserAdministrationImpl implements UserAdministration { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#renameGroup(org.wamblee.usermgt.Group, * java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * @param aGroupName DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public void renameGroup(Group aGroup, String aGroupName) - throws UserMgtException { + 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. @@ -227,12 +331,20 @@ public class UserAdministrationImpl implements UserAdministration { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#addUserToGroup(org.wamblee.usermgt.User, * org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public void addUserToGroup(User aUser, Group aGroup) - throws UserMgtException { + throws UserMgtException { checkUser(aUser); checkGroup(aGroup); aUser.addGroup(aGroup); @@ -241,12 +353,20 @@ public class UserAdministrationImpl implements UserAdministration { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministration#removeUserFromGroup(org.wamblee.usermgt.User, * org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ public void removeUserFromGroup(User aUser, Group aGroup) - throws UserMgtException { + throws UserMgtException { checkUser(aUser); checkGroup(aGroup); aUser.removeGroup(aGroup); @@ -254,7 +374,10 @@ public class UserAdministrationImpl implements UserAdministration { } /** + * DOCUMENT ME! + * * @param aUser + * * @throws UserMgtException */ private void checkUser(User aUser) throws UserMgtException { @@ -264,7 +387,10 @@ public class UserAdministrationImpl implements UserAdministration { } /** + * DOCUMENT ME! + * * @param aGroup + * * @throws UserMgtException */ private void checkGroup(Group aGroup) throws UserMgtException { @@ -272,18 +398,28 @@ public class UserAdministrationImpl implements UserAdministration { throw new UserMgtException(UNKNOWN_GROUP, aGroup); } } - + /* (non-Javadoc) * @see org.wamblee.usermgt.UserAdministration#getUserCount() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int getUserCount() { - return users.size(); + return users.size(); } - + /* (non-Javadoc) * @see org.wamblee.usermgt.UserAdministration#getGroupCount() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int getGroupCount() { - return groups.size(); + return groups.size(); } } diff --git a/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java b/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java index fb3378cf..8c93cbd1 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java +++ b/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java @@ -1,55 +1,82 @@ /* * 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 { +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + - public UserGroupRepositoryComponent(String aName) { - super(aName, new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" } , - createProvided(), createRequired()); - +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class UserGroupRepositoryComponent extends SpringComponent { +/** + * Creates a new UserGroupRepositoryComponent object. + * + * @param aName DOCUMENT ME! + */ + public UserGroupRepositoryComponent(String aName) { + super(aName, + new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" }, + createProvided(), createRequired()); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createRequired() { Map required = new HashMap(); - required.put(new DefaultRequiredInterface("sessionFactory", SessionFactory.class), "sessionFactory"); + required.put(new DefaultRequiredInterface("sessionFactory", + SessionFactory.class), "sessionFactory"); + return required; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createProvided() { - Map provided = new HashMap(); - 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; + Map provided = new HashMap(); + 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/security/src/main/java/org/wamblee/usermgt/UserMgtException.java b/security/src/main/java/org/wamblee/usermgt/UserMgtException.java index e2f057c0..8614e0a4 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserMgtException.java +++ b/security/src/main/java/org/wamblee/usermgt/UserMgtException.java @@ -1,56 +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.usermgt; import java.util.EnumMap; + /** - * User management exception. + * User management exception. * * @author Erik Brakkee */ public class UserMgtException extends Exception { - - static final long serialVersionUID = 5585349754997507529L; - /** - * Possible causes for the exception. - * + * DOCUMENT ME! */ - 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 - } - + static final long serialVersionUID = 5585349754997507529L; + /** - * Mapping of enum to exception message text. + * Mapping of enum to exception message text. */ - private static final EnumMap MESSAGES = new EnumMap(Reason.class); - + private static final EnumMap MESSAGES = new EnumMap(Reason.class); + static { MESSAGES.put(Reason.UNKNOWN_USER, "Unknown user"); MESSAGES.put(Reason.UNKNOWN_GROUP, "Unknown group"); @@ -61,68 +44,117 @@ public class UserMgtException extends Exception { 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.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. + * Cause of the exception. */ - private Reason cause; - + private Reason cause; + /** - * User or null if no user is relevant for the problem. + * User or null if no user is relevant for the problem. */ - private User user; - + private User user; + /** - * Group or null if no group is relevant for the problem. + * Group or null if no group is relevant for the problem. */ - private Group group; + private Group group; +/** + * Creates a new UserMgtException object. + * + * @param aCause DOCUMENT ME! + * @param aMessage DOCUMENT ME! + */ public UserMgtException(Reason aCause, String aMessage) { super(MESSAGES.get(aCause) + ": " + aMessage); - cause = aCause; + cause = aCause; } - + +/** + * Creates a new UserMgtException object. + * + * @param aCause DOCUMENT ME! + * @param aUser DOCUMENT ME! + */ public UserMgtException(Reason aCause, User aUser) { this(aCause, "for user '" + aUser.getName() + "'"); - user = aUser; + user = aUser; } - + +/** + * Creates a new UserMgtException object. + * + * @param aCause DOCUMENT ME! + * @param aGroup DOCUMENT ME! + */ public UserMgtException(Reason aCause, Group aGroup) { this(aCause, "for group '" + aGroup.getName() + "'"); - group = aGroup; + group = aGroup; } - + +/** + * Creates a new UserMgtException object. + * + * @param aCause DOCUMENT ME! + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + */ public UserMgtException(Reason aCause, User aUser, Group aGroup) { - this(aCause, "for user '" + aUser.getName() + "' and group '" + aGroup.getName() + "'"); - 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. + * Gets the cause of the problem. + * + * @return Cause. */ public Reason getReason() { - return cause; + return cause; } - + /** - * Gets the user for which the problem occurred. - * @return User or null if not applicable. + * Gets the user for which the problem occurred. + * + * @return User or null if not applicable. */ public User getUser() { - return user; + return user; } - + /** - * Gets the group for which the problem occured. - * @return Group or null if not applicable. + * Gets the group for which the problem occured. + * + * @return Group or null if not applicable. */ public Group getGroup() { return group; - } + } + +/** + * 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; + } } diff --git a/security/src/main/java/org/wamblee/usermgt/UserSet.java b/security/src/main/java/org/wamblee/usermgt/UserSet.java index ac3f5a70..6c04196c 100644 --- a/security/src/main/java/org/wamblee/usermgt/UserSet.java +++ b/security/src/main/java/org/wamblee/usermgt/UserSet.java @@ -1,23 +1,23 @@ /* * 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 @@ -26,58 +26,96 @@ import java.util.Set; * @author Erik Brakkee */ public interface UserSet { - /** - * Creates a user. - * @param aUsername User name. - * @param aPassword Password. + * 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; - + * + * @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. + * Must be called whenever a user object has been modified to + * notify the user set. + * + * @param aUser Modified user. */ - void userModified(User aUser); - + void userModified(User aUser); + /** - * Finds user. - * @param aName Username. - * @return User or null if not found. + * 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. + * Checks if a user exists. + * + * @param aUser User. + * + * @return True iff the user exists. */ - boolean contains(User aUser); - + 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. + * 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. + * + * @return DOCUMENT ME! */ boolean add(User aUser); - + /** - * Removes a user. If the user does not exist, nothing happens. + * Removes a user. If the user does not exist, nothing happens. + * * @param aUser + * + * @return DOCUMENT ME! */ boolean remove(User aUser); - + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Lists the current users. * @return Users. */ - Set list(); - + Set list(); + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * Lists the users belonging to a particular group. * @param aGroup Group. * @return Groups. @@ -85,8 +123,9 @@ public interface UserSet { Set list(Group aGroup); /** - * - * @return The number of users. + * DOCUMENT ME! + * + * @return The number of users. */ - int size(); + int size(); } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java b/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java index 150a8447..0943acd4 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,15 +15,15 @@ */ 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; @@ -33,42 +33,76 @@ 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; +import java.io.IOException; + +import javax.sql.DataSource; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class AuthorizationComponent extends DefaultContainer { + /** + * DOCUMENT ME! + */ + private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface("transactionManager", + PlatformTransactionManager.class); + + /** + * DOCUMENT ME! + */ + private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface("hibernateTemplate", + HibernateTemplate.class); - 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); + /** + * DOCUMENT ME! + */ + private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface("authorizationService", + AuthorizationService.class); +/** + * Creates a new AuthorizationComponent object. + * + * @param aName DOCUMENT ME! + * @param aExposeInternals DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public AuthorizationComponent(String aName, boolean aExposeInternals) - throws IOException { + throws IOException { super(aName); - + ObjectConfiguration authConfig = new ObjectConfiguration(AuthorizationMappingFiles.class); authConfig.getSetterConfig().initAllSetters(); - addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig); + addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig); Component hibernate = new HibernateComponent("hibernate"); addComponent(hibernate); - Component authorization = new AuthorizationLightComponent("authorization"); + Component authorization = new AuthorizationLightComponent( + "authorization"); addComponent(authorization); - addRequiredInterface(new DefaultRequiredInterface("datasource", DataSource.class)); + addRequiredInterface(new DefaultRequiredInterface("datasource", + DataSource.class)); addRequiredInterface(new DefaultRequiredInterface("userAccessor", UserAccessor.class)); - addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class)); + addRequiredInterface(new DefaultRequiredInterface("ormconfig", + ORMappingConfig.class)); if (aExposeInternals) { addProvidedInterface(TRANSACTION_MGR); addProvidedInterface(HIBERNATE_TEMPLATE); } + addProvidedInterface(AUTHORIZATION_SERVICE); } } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java b/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java index e7b0c963..2a77fd82 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,52 +15,70 @@ */ 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; +import java.util.HashMap; +import java.util.Map; + + /** - * 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. - * + * 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 { - +/** + * Creates a new AuthorizationLightComponent object. + * + * @param aName DOCUMENT ME! + */ public AuthorizationLightComponent(String aName) { - super( - aName, - new String[] { "spring/org.wamblee.security.authorization.xml" }, - createProvided(), createRequired()); + super(aName, + new String[] { "spring/org.wamblee.security.authorization.xml" }, + createProvided(), createRequired()); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createRequired() { Map required = new HashMap(); required.put(new DefaultRequiredInterface("userArccessor", UserAccessor.class), UserAccessor.class.getName()); required.put(new DefaultRequiredInterface("hibernateTemplate", HibernateTemplate.class), HibernateTemplate.class.getName()); + return required; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createProvided() { Map provided = new HashMap(); provided.put(AuthorizationService.class.getName(), - new DefaultProvidedInterface(AuthorizationService.class - .getName(), AuthorizationService.class)); + new DefaultProvidedInterface(AuthorizationService.class.getName(), + AuthorizationService.class)); + return provided; } } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java b/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java index 957ee44d..7bd02d75 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java @@ -1,120 +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.usermgt.hibernate; +import org.wamblee.persistence.hibernate.HibernateSupport; + +import org.wamblee.usermgt.Group; +import org.wamblee.usermgt.GroupSet; + 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. + * Set of groups backed by the database. * * @author Erik Brakkee */ public class HibernateGroupSet extends HibernateSupport implements GroupSet { - - + /** + * DOCUMENT ME! + */ private static final String QUERY_FIND_BY_NAME = "findGroupByName"; - + + /** + * DOCUMENT ME! + */ private static final String PARAM_NAME = "name"; - + + /** + * DOCUMENT ME! + */ private static final String QUERY_COUNT_GROUPS = "countGroups"; - + +/** + * Creates a new HibernateGroupSet object. + */ public HibernateGroupSet() { // Empty } - + /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + */ public void groupModified(Group aGroup) { - assert aGroup.getPrimaryKey() != null; - super.merge(aGroup); + assert aGroup.getPrimaryKey() != null; + super.merge(aGroup); } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#find(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws RuntimeException DOCUMENT ME! + */ 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 + "'"); + 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; + + if (list.size() == 0) { + return null; } - return new Group((Group)list.get(0)); + + return new Group((Group) list.get(0)); } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean contains(Group aGroup) { - return find(aGroup.getName()) != null; + return find(aGroup.getName()) != null; } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean add(Group aGroup) { - assert aGroup.getPrimaryKey() == null; - if ( contains(aGroup) ) { - return false; + assert aGroup.getPrimaryKey() == null; + + if (contains(aGroup)) { + return false; } + super.merge(aGroup); - return true; + + return true; } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean remove(Group aGroup) { - assert aGroup.getPrimaryKey() != null; - if ( !contains(aGroup)) { - return false; + assert aGroup.getPrimaryKey() != null; + + if (!contains(aGroup)) { + return false; } - Group group = (Group) getHibernateTemplate().merge(aGroup); + + Group group = (Group) getHibernateTemplate().merge(aGroup); getHibernateTemplate().delete(group); - aGroup.setPrimaryKey(null); + aGroup.setPrimaryKey(null); aGroup.setPersistedVersion(-1); - return true; + + return true; } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#list() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set list() { - Set groups = new TreeSet(); - List list = getHibernateTemplate().loadAll(Group.class); - for (Group group: list) { + Set groups = new TreeSet(); + List list = getHibernateTemplate().loadAll(Group.class); + + for (Group group : list) { groups.add(new Group(group)); } - return groups; + + return groups; } /* (non-Javadoc) * @see org.wamblee.usermgt.GroupSet#size() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int size() { - Long result = (Long) getHibernateTemplate().findByNamedQuery(QUERY_COUNT_GROUPS).get(0); - return result.intValue(); + Long result = (Long) getHibernateTemplate() + .findByNamedQuery(QUERY_COUNT_GROUPS).get(0); + + return result.intValue(); } } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java b/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java index df13cac1..c0dd4021 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java @@ -1,92 +1,116 @@ /* * 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; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + + /** * User set backed by the database. * * @author Erik Brakkee */ public class HibernateUserSet extends AbstractUserSet { - + /** + * DOCUMENT ME! + */ private static final String QUERY_FIND_BY_NAME = "findUserByName"; + /** + * DOCUMENT ME! + */ private static final String QUERY_FIND_BY_GROUP_NAME = "findUserByGroupName"; + /** + * DOCUMENT ME! + */ 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. + * DOCUMENT ME! */ - private Cache cache; - - /** - * Spring hibernate support. + private static final String QUERY_COUNT_USERS = "countUsers"; + + /** + * Cache of users. Every user in the cache has its password + * validator and encoder set. */ - private HibernateSupport hibernateSupport; + private Cache cache; /** + * Spring hibernate support. + */ + private HibernateSupport hibernateSupport; + +/** * Constructs a user set backed by the database. * @param aCache User cache to use. */ - public HibernateUserSet(Cache aCache, - NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) { + public HibernateUserSet(Cache aCache, + NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) { super(aPasswordValidator, aPasswordEncoder); - cache = aCache; - hibernateSupport = new HibernateSupport(); + cache = aCache; + hibernateSupport = new HibernateSupport(); } - + /** - * Sets the session factory. - * @param aFactory Session factory. + * Sets the session factory. + * + * @param aFactory Session factory. */ - public void setSessionFactory(SessionFactory aFactory) { + public void setSessionFactory(SessionFactory aFactory) { hibernateSupport.setSessionFactory(aFactory); } - + /** - * Gets the hibernate template. - * @return Hibernate template. + * Gets the hibernate template. + * + * @return Hibernate template. */ - private HibernateTemplate getHibernateTemplate() { + private HibernateTemplate getHibernateTemplate() { return hibernateSupport.getHibernateTemplate(); } - + /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + */ public void userModified(User aUser) { assert aUser.getPrimaryKey() != null; hibernateSupport.merge(aUser); @@ -97,108 +121,174 @@ public class HibernateUserSet extends AbstractUserSet { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#find(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws RuntimeException DOCUMENT ME! + */ 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); + + 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!"); + "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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean contains(User aUser) { return find(aUser.getName()) != null; } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set list() { - Set users = new TreeSet(); - List list = getHibernateTemplate().loadAll(User.class); + Set users = new TreeSet(); + List 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) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Set list(Group aGroup) { - Set users = new TreeSet(); - List list = getHibernateTemplate().findByNamedQueryAndNamedParam( - QUERY_FIND_BY_GROUP_NAME, PARAM_NAME, aGroup.getName()); + Set users = new TreeSet(); + List 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() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int size() { - Long result = (Long)getHibernateTemplate().findByNamedQuery(QUERY_COUNT_USERS).get(0); - return result.intValue(); + Long result = (Long) getHibernateTemplate() + .findByNamedQuery(QUERY_COUNT_USERS).get(0); + + return result.intValue(); } } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java b/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java index b6da3380..0349c388 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,13 +15,12 @@ */ 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; @@ -31,46 +30,85 @@ 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; +import java.io.IOException; + +import javax.sql.DataSource; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class UserAdministrationComponent extends DefaultContainer { + /** + * DOCUMENT ME! + */ + private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface("transactionManager", + PlatformTransactionManager.class); - 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); + /** + * DOCUMENT ME! + */ + private ProvidedInterface USER_CACHE = new DefaultProvidedInterface("userCache", + EhCache.class); + /** + * DOCUMENT ME! + */ + private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface("hibernateTemplate", + HibernateTemplate.class); + + /** + * DOCUMENT ME! + */ + private ProvidedInterface USER_MGT = new DefaultProvidedInterface("usermgt", + UserAdministration.class); + +/** + * Creates a new UserAdministrationComponent object. + * + * @param aName DOCUMENT ME! + * @param aExposeInternals DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public UserAdministrationComponent(String aName, boolean aExposeInternals) - throws IOException { + throws IOException { super(aName); - - ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); + + ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); mappingFilesConfig.getSetterConfig().initAllSetters(); - addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig); + addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), + mappingFilesConfig); Component hibernate = new HibernateComponent("hibernate"); addComponent(hibernate); - Component repository = new UserGroupRepositoryComponent("usersgroups"); + Component repository = new UserGroupRepositoryComponent( + "usersgroups"); addComponent(repository); - Component usermgt = new UserAdministrationLightComponent("usermgtlight"); + Component usermgt = new UserAdministrationLightComponent( + "usermgtlight"); addComponent(usermgt); addRequiredInterface(new DefaultRequiredInterface("datasource", DataSource.class)); - addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class)); + addRequiredInterface(new DefaultRequiredInterface("ormconfig", + ORMappingConfig.class)); if (aExposeInternals) { addProvidedInterface(TRANSACTION_MGR); addProvidedInterface(USER_CACHE); addProvidedInterface(HIBERNATE_TEMPLATE); } + addProvidedInterface(USER_MGT); } } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java b/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java index 1a06ae7a..6d2d4d98 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java @@ -1,57 +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.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; +import java.util.HashMap; +import java.util.Map; + + /** - * 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 + * 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() ); +/** + * Creates a new UserAdministrationLightComponent object. + * + * @param aName DOCUMENT ME! + */ + public UserAdministrationLightComponent(String aName) { + super(aName, + new String[] { "spring/org.wamblee.security.usermgt.xml" }, + createProvided(), createRequired()); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createRequired() { - Map required = new HashMap(); - required.put(new DefaultRequiredInterface("userSet", UserSet.class), UserSet.class.getName()); - required.put(new DefaultRequiredInterface("groupSet", GroupSet.class), GroupSet.class.getName()); - return required; + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("userSet", UserSet.class), + UserSet.class.getName()); + required.put(new DefaultRequiredInterface("groupSet", GroupSet.class), + GroupSet.class.getName()); + + return required; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createProvided() { Map provided = new HashMap(); - provided.put(UserAdministration.class.getName(), new DefaultProvidedInterface("org.wamblee.usermgt.UserAdministration", + provided.put(UserAdministration.class.getName(), + new DefaultProvidedInterface( + "org.wamblee.usermgt.UserAdministration", UserAdministration.class)); + return provided; } } diff --git a/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java b/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java index 8d523c2e..629f6170 100644 --- a/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java +++ b/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java @@ -1,40 +1,45 @@ /* * 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 org.wamblee.persistence.hibernate.HibernateMappingFiles; + import java.util.Collections; -import org.wamblee.persistence.hibernate.HibernateMappingFiles; /** - * Hibernate mapping files for user management. + * 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" - }); +/** + * Creates a new UsermgtHibernateMappingFiles object. + */ + public UsermgtHibernateMappingFiles() { + super(new String[] { "hbm/Group.hbm.xml", "hbm/User.hbm.xml" }); } - - public UsermgtHibernateMappingFiles(String[] aFiles) { - this(); + +/** + * Creates a new UsermgtHibernateMappingFiles object. + * + * @param aFiles DOCUMENT ME! + */ + public UsermgtHibernateMappingFiles(String[] aFiles) { + this(); Collections.addAll(this, aFiles); } } diff --git a/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java b/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java index 5ec36f7e..fcc29344 100644 --- a/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java +++ b/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java @@ -1,177 +1,247 @@ /* * 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 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. + * 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; - } - + /** + * DOCUMENT ME! + */ + private AuthorizationRule rule1; + + /** + * DOCUMENT ME! + */ + private AuthorizationRule rule2; + + /** + * DOCUMENT ME! + */ + private AuthorizationRule rule3; + + /** + * DOCUMENT ME! + */ + private AuthorizationService service; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected AuthorizationService getService() { + return service; + } + /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @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); + + 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(); + + /** + * DOCUMENT ME! + */ + protected void resetTestRules() { + ((TestAuthorizationRule) rule1).reset(); + ((TestAuthorizationRule) rule2).reset(); + ((TestAuthorizationRule) rule3).reset(); } - - protected UserAccessor createUserAccessor() { - return new TestUserAccessor(); + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected UserAccessor createUserAccessor() { + return new TestUserAccessor(); } /** - * Creates an authorization service with some rules for testing. . - * @return Authorization service. + * Creates an authorization service with some rules for testing. . + * + * @return Authorization service. */ protected AuthorizationService createService() { - DefaultAuthorizationService service = new DefaultAuthorizationService() ; + DefaultAuthorizationService service = new DefaultAuthorizationService(); service.setUserAccessor(createUserAccessor()); + return service; } - - protected AuthorizationRule createRule(AuthorizationResult aResult, String aGroup, String aPath, Class aOperation) { + + /** + * DOCUMENT ME! + * + * @param aResult DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * @param aPath DOCUMENT ME! + * @param aOperation DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected AuthorizationRule createRule(AuthorizationResult aResult, + String aGroup, String aPath, Class aOperation) { return new TestAuthorizationRule(aResult, aGroup, aPath, aOperation); } - - protected void checkMatchCount(int aCount, AuthorizationRule aRule) { - assertEquals( aCount, ((TestAuthorizationRule)aRule).getMatchCount()); + + /** + * DOCUMENT ME! + * + * @param aCount DOCUMENT ME! + * @param aRule DOCUMENT ME! + */ + protected void checkMatchCount(int aCount, AuthorizationRule aRule) { + assertEquals(aCount, ((TestAuthorizationRule) aRule).getMatchCount()); } - - protected Object createResource(String aPath) { + + /** + * DOCUMENT ME! + * + * @param aPath DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Object createResource(String aPath) { return new TestResource(aPath); } - - protected void checkRuleCount(int aCount) { + + /** + * DOCUMENT ME! + * + * @param aCount DOCUMENT ME! + */ + protected void checkRuleCount(int aCount) { // Empty } - + /** - * Several checks to verify the outcome of matching against the first rule. - * + * Several checks to verify the outcome of matching against the + * first rule. */ - public void testFirstRuleGrants() { - assertTrue( service.isAllowed(createResource("/oni/xyz.jpg"), new ReadOperation())); + public void testFirstRuleGrants() { + assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), + new ReadOperation())); checkMatchCount(1, rule1); - assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new WriteOperation())); + assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), + new WriteOperation())); checkMatchCount(2, rule1); - assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new DeleteOperation())); + assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), + new DeleteOperation())); checkMatchCount(3, rule1); - assertTrue(service.isAllowed(createResource("/oni/xyz.jpg"), new CreateOperation())); + 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. - * + * 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())); + 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. - * + * 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); + public void testThirdRuleGrants() { + assertTrue(service.isAllowed(createResource("/abc/xyz.jpg"), + new WriteOperation())); + checkMatchCount(0, rule1); checkMatchCount(0, rule2); - checkMatchCount(1, rule3); + checkMatchCount(1, rule3); } - + /** - * Removes a rule and checks it is removed. - * + * Removes a rule and checks it is removed. */ - public void testRemoveRule() { + 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())); + 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. - * + * 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())); + 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. - * + * Gets the rules. Verifies that all rules are obtained. */ - public void testGetRules() { + public void testGetRules() { AuthorizationRule[] rules = service.getRules(); - assertEquals(3, rules.length); + assertEquals(3, rules.length); } - + /** - * Verifies that when no rules match, access is denied. - * + * Verifies that when no rules match, access is denied. */ - public void testNoRulesSupportResource() { - assertFalse(service.isAllowed(createResource("/xyxyxyxy"), new ReadOperation())); - checkMatchCount(0, rule1); + public void testNoRulesSupportResource() { + assertFalse(service.isAllowed(createResource("/xyxyxyxy"), + new ReadOperation())); + checkMatchCount(0, rule1); checkMatchCount(0, rule2); - checkMatchCount(0, rule3); + checkMatchCount(0, rule3); } } diff --git a/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java b/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java index a1023ac6..d33b65d7 100644 --- a/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java +++ b/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java @@ -1,84 +1,86 @@ /* * 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. + * Test of the operation registry. * * @author Erik Brakkee */ public class DefaultOperationRegistryTest extends TestCase { - - private OperationRegistry registry; - + /** + * DOCUMENT ME! + */ + private OperationRegistry registry; + /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { - registry = new DefaultOperationRegistry(new Operation[] { - new AllOperation(), - new ReadOperation(), - new WriteOperation(), - new DeleteOperation(), - new CreateOperation() - }); + new AllOperation(), new ReadOperation(), + new WriteOperation(), new DeleteOperation(), + new CreateOperation() + }); } - + /** - * Tests encoding and decoding of no operations. - * + * Tests encoding and decoding of no operations. */ - public void testEncodeDecodeNooperations() { + 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. - * + * Verifies that encoding of operations into a string works. */ - public void testEncode() { - assertEquals("read,write", registry.encode(new Operation[] { new ReadOperation(), new WriteOperation() })); + public void testEncode() { + assertEquals("read,write", + registry.encode( + new Operation[] { new ReadOperation(), new WriteOperation() })); } - + /** - * Verifies that decoding of operation from a string works. - * + * Verifies that decoding of operation from a string works. */ - public void testDecode() { + public void testDecode() { Operation[] operations = registry.decode(Object.class, "read,write"); - assertTrue( operations[0] instanceof ReadOperation); - assertTrue( operations[1] instanceof WriteOperation); + 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. - * + * 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) { + public void testDecodeUnknownOperation() { + try { + registry.decode(Object.class, "bla"); + fail(); + } catch (IllegalArgumentException e) { // ok } } diff --git a/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java b/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java index cf83b289..f9f293ee 100644 --- a/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java +++ b/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java @@ -1,39 +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; + /** - * Test for regular expression matching. + * Test for regular expression matching. * * @author Erik Brakkee */ public class RegexpPathConditionTest extends TestCase { - /** - * Various tests. - * + * 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")); + 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/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java b/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java index 2e64098d..ce1bfb46 100644 --- a/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java +++ b/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java @@ -1,32 +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.authorization; import junit.framework.TestCase; + /** - * Tests for StartsWithPathCondition. + * Tests for StartsWithPathCondition. * * @author Erik Brakkee */ public class StartsWithPathConditionTest extends TestCase { - /** - * Various tests. + * Various tests. */ public void testMatches() { PathCondition cond = new StartsWithPathCondition("/hallo"); diff --git a/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java b/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java index 3644dc83..e6cf01db 100644 --- a/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java +++ b/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java @@ -1,19 +1,18 @@ /* * 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; @@ -21,55 +20,94 @@ 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. + * 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. + * Counts the number of matches. */ - private int matches = 0; + private int matches = 0; - public TestAuthorizationRule( AuthorizationResult aResult, String aGroup, - String aPath, Class aOperation) { - super(aResult, new GroupUserCondition(aGroup), - new StartsWithPathCondition(aPath), TestResource.class, new IsaOperationCondition(aOperation)); +/** + * Creates a new TestAuthorizationRule object. + * + * @param aResult DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * @param aPath DOCUMENT ME! + * @param aOperation DOCUMENT ME! + */ + public TestAuthorizationRule(AuthorizationResult aResult, String aGroup, + String aPath, Class aOperation) { + super(aResult, new GroupUserCondition(aGroup), + new StartsWithPathCondition(aPath), TestResource.class, + new IsaOperationCondition(aOperation)); } - - protected TestAuthorizationRule() { + +/** + * Creates a new TestAuthorizationRule object. + */ + protected TestAuthorizationRule() { super(); } - + /* (non-Javadoc) * @see org.wamblee.security.authorization.UrlAuthorizationRule#getPath(java.lang.Object) */ + /** + * DOCUMENT ME! + * + * @param aResource DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected String getResourcePath(Object aResource) { - return ((TestResource)aResource).getPath(); + 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) */ + /** + * DOCUMENT ME! + * + * @param aResource DOCUMENT ME! + * @param anOperation DOCUMENT ME! + * @param aUser DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @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++; + 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; + + return result; } - - public int getMatchCount() { - return matches; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public int getMatchCount() { + return matches; } - - public void reset() { - matches = 0; + + /** + * DOCUMENT ME! + */ + public void reset() { + matches = 0; } - } diff --git a/security/src/test/java/org/wamblee/security/authorization/TestResource.java b/security/src/test/java/org/wamblee/security/authorization/TestResource.java index 4712c42c..386a9844 100644 --- a/security/src/test/java/org/wamblee/security/authorization/TestResource.java +++ b/security/src/test/java/org/wamblee/security/authorization/TestResource.java @@ -1,35 +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; /** - * A test resource for authorization. + * A test resource for authorization. * * @author Erik Brakkee */ public class TestResource { + /** + * DOCUMENT ME! + */ + private String path; - private String path; - - public TestResource(String aPath) { - path = aPath; +/** + * Creates a new TestResource object. + * + * @param aPath DOCUMENT ME! + */ + public TestResource(String aPath) { + path = aPath; } - - public String getPath() { - return path; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getPath() { + return path; } } diff --git a/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java b/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java index 02e09020..b4d89097 100644 --- a/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java +++ b/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java @@ -1,24 +1,24 @@ /* * 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; @@ -30,37 +30,59 @@ 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. + * 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"; + /** + * DOCUMENT ME! + */ + private static final String USER = "erik"; + + /** + * DOCUMENT ME! + */ private static final String PASSWORD = "abc123"; + + /** + * DOCUMENT ME! + */ private static final String GROUP = "users"; /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAccessor#getCurrentUser() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws RuntimeException DOCUMENT ME! + */ 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") - ); + 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/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java b/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java index 4e66ed86..05ff8591 100644 --- a/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java +++ b/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java @@ -1,91 +1,105 @@ /* * 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 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}. + * 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. - * + * 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); + public void testConstructWithUndecidedResult() { + try { + new TestAuthorizationRule(UNDECIDED, "users", "/path", + ReadOperation.class); fail(); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { // ok } } - + /** - * Constructs the rule with a result of UNSUPPORTED_RESOURCE. Verifies that an IllegalArgumentException - * is thrown. - * + * 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); + public void testConstructWithUnsupportedResult() { + try { + new TestAuthorizationRule(UNSUPPORTED_RESOURCE, "users", "/path", + ReadOperation.class); fail(); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { // ok } } - + /** - * Constructs the authorization rule and applies it to an unsupported object type. - * Verifies that the result is UNSUPPORTED_RESOURCE. - * + * 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 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(); - + + /** + * DOCUMENT ME! + */ + 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)); - + 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)); - + assertEquals(UNDECIDED, + rule.isAllowed(new TestResource("/path"), new ReadOperation(), user)); + // operation does not match. - assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path/"), new WriteOperation(), user)); - + 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)); + AuthorizationRule rule2 = new TestAuthorizationRule(GRANTED, "users2", + "/path/", ReadOperation.class); + assertEquals(UNDECIDED, + rule2.isAllowed(new TestResource("/path/a"), new ReadOperation(), + user)); } - } diff --git a/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java b/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java index b1a36934..11b9da50 100644 --- a/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java +++ b/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java @@ -1,33 +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.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; @@ -36,60 +40,110 @@ 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; +import java.sql.SQLException; + + /** * Unit test for the persistent authorization service. - * + * * @author Erik Brakkee */ -public class PersistentAuthorizationServiceTest extends - AuthorizationServiceTest { - - private static final Logger LOGGER = Logger - .getLogger(PersistentAuthorizationServiceTest.class); +public class PersistentAuthorizationServiceTest extends AuthorizationServiceTest { + /** + * DOCUMENT ME! + */ + private static final Logger LOGGER = Logger.getLogger(PersistentAuthorizationServiceTest.class); + /** + * DOCUMENT ME! + */ private static final String SERVICE_TABLE = "AUTHORIZATION_SERVICE"; + + /** + * DOCUMENT ME! + */ private static final String RULES_TABLE = "AUTHORIZATION_RULES"; + + /** + * DOCUMENT ME! + */ private static final String SERVICE_RULES_TABLE = "AUTHORIZATION_SERVICE_RULES"; + + /** + * DOCUMENT ME! + */ private static final String OPERATIONCOND_TABLE = "OPERATION_CONDITIONS"; + + /** + * DOCUMENT ME! + */ private static final String PATHCOND_TABLE = "PATH_CONDITIONS"; + + /** + * DOCUMENT ME! + */ private static final String USERCOND_TABLE = "USER_CONDITIONS"; + /** + * DOCUMENT ME! + */ private DefaultContainer container; + + /** + * DOCUMENT ME! + */ private Scope scope; + /** + * DOCUMENT ME! + */ private DatabaseTesterComponent databaseTester; + + /** + * DOCUMENT ME! + */ private UserAccessor userAccessor; + + /** + * DOCUMENT ME! + */ private HibernateTemplate hibernateTemplate; + + /** + * DOCUMENT ME! + */ private AuthorizationService authorizationService; + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { - container = new DefaultContainer("top"); DatabaseComponentFactory.addDatabaseConfig(container); container.addComponent(new DatasourceComponent("datasource")); - ClassConfiguration useraccessorConfig = new ClassConfiguration( - TestUserAccessor.class); + + ClassConfiguration useraccessorConfig = new ClassConfiguration(TestUserAccessor.class); useraccessorConfig.getObjectConfig().getSetterConfig().initAllSetters(); container.addComponent("userAccessor", useraccessorConfig); - container.addComponent(new AuthorizationComponent("authorization", - true)); + container.addComponent(new AuthorizationComponent("authorization", true)); - ClassConfiguration dbtesterConfig = new ClassConfiguration( - DatabaseTesterComponent.class); + 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"); + 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(); @@ -99,78 +153,120 @@ public class PersistentAuthorizationServiceTest extends super.setUp(); } + /** + * DOCUMENT ME! + * + * @param aDatabaseTester DOCUMENT ME! + */ public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { databaseTester = aDatabaseTester; } + /** + * DOCUMENT ME! + * + * @param aUserAccessor DOCUMENT ME! + */ public void setUserAccessor(UserAccessor aUserAccessor) { userAccessor = aUserAccessor; } + /** + * DOCUMENT ME! + * + * @param aHibernateTemplate DOCUMENT ME! + */ public void setHibernateTemplate(HibernateTemplate aHibernateTemplate) { hibernateTemplate = aHibernateTemplate; } + /** + * DOCUMENT ME! + * + * @param aAuthorizationService DOCUMENT ME! + */ public void setAuthorizationService( - AuthorizationService aAuthorizationService) { + AuthorizationService aAuthorizationService) { authorizationService = aAuthorizationService; } /* * (non-Javadoc) - * + * * @see * org.wamblee.security.authorization.AuthorizationServiceTest#createService * () */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected AuthorizationService createService() { - PersistentAuthorizationService service = new PersistentAuthorizationService( - "DEFAULT", hibernateTemplate, createUserAccessor(), 10000); + PersistentAuthorizationService service = new PersistentAuthorizationService("DEFAULT", + hibernateTemplate, createUserAccessor(), 10000); + return service; } /* * (non-Javadoc) - * + * * @see * org.wamblee.security.authorization.AuthorizationServiceTest#checkRuleCount * (int) */ + /** + * DOCUMENT ME! + * + * @param aCount DOCUMENT ME! + * + * @throws RuntimeException DOCUMENT ME! + */ @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(SERVICE_RULES_TABLE)); assertEquals(aCount, databaseTester.getTableSize(USERCOND_TABLE)); assertEquals(aCount, databaseTester.getTableSize(PATHCOND_TABLE)); - assertEquals(aCount, databaseTester - .getTableSize(OPERATIONCOND_TABLE)); + assertEquals(aCount, + databaseTester.getTableSize(OPERATIONCOND_TABLE)); } catch (SQLException e) { throw new RuntimeException(e); } - } - public void testSchemaExport() { + /** + * DOCUMENT ME! + */ + public void testSchemaExport() { Configuration config = new Configuration(); - for (String mappingFile: new AuthorizationMappingFiles()) { - config.addResource(mappingFile); + + for (String mappingFile : new AuthorizationMappingFiles()) { + config.addResource(mappingFile); } - config.setProperty("hibernate.dialect", MySQL5InnoDBDialect.class.getName()); + + config.setProperty("hibernate.dialect", + MySQL5InnoDBDialect.class.getName()); + SchemaExport exporter = new SchemaExport(config); exporter.setOutputFile("target/mysql5.schema.sql"); - exporter.create(true,false); + exporter.create(true, false); } + /** + * DOCUMENT ME! + */ public void testPerformance() { - PersistentAuthorizationService service = (PersistentAuthorizationService) getService(); - int n = 1000; - long time = System.currentTimeMillis(); + int n = 1000; + long time = System.currentTimeMillis(); + for (int i = 0; i < n; i++) { testFirstRuleGrants(); resetTestRules(); @@ -180,8 +276,9 @@ public class PersistentAuthorizationServiceTest extends resetTestRules(); testNoRulesSupportResource(); } - LOGGER.info("Executed " + 4 * n + " authorization checks in " - + (float) (System.currentTimeMillis() - time) / (float) 1000 - + " seconds."); + + LOGGER.info("Executed " + (4 * n) + " authorization checks in " + + ((float) (System.currentTimeMillis() - time) / (float) 1000) + + " seconds."); } } diff --git a/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java b/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java index 6760efe9..647a0275 100644 --- a/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java +++ b/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java @@ -1,31 +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.encryption; import junit.framework.TestCase; + /** - * Tests for the message digester. + * Tests for the message digester. * * @author Erik Brakkee */ public class MessageDigesterTest extends TestCase { - - public void testMd5HexEncoding() { - assertEquals("e99a18c428cb38d5f260853678922e03", new Md5HexMessageDigester().hash("abc123")); + /** + * DOCUMENT ME! + */ + public void testMd5HexEncoding() { + assertEquals("e99a18c428cb38d5f260853678922e03", + new Md5HexMessageDigester().hash("abc123")); } } diff --git a/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java b/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java index 03329d1d..e71b3e31 100644 --- a/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java +++ b/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java @@ -1,188 +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.usermgt; +import junit.framework.TestCase; + 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. + * implementations of group set. */ public class InMemoryGroupSetTest extends TestCase { - - protected GroupSet groups; - /** - * This method must be overriden in subclasses. - * @return New group set object. + * DOCUMENT ME! */ - protected GroupSet createGroupSet() { - return new InMemoryGroupSet(); + 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() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { super.setUp(); - groups = createGroupSet(); - checkGroupCount(0); + groups = createGroupSet(); + checkGroupCount(0); } - - - + /** - * Additional check to be implemented by a subclass. - * @param aGroup Group to check for existence. + * Additional check to be implemented by a subclass. + * + * @param aGroup Group to check for existence. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkGroupExists(String aGroup) throws SQLException { + protected void checkGroupExists(String aGroup) throws SQLException { // Empty } - + /** - * Additional check to be implemented by a subclass. - * @param aGroup Group to check for non-existence. + * Additional check to be implemented by a subclass. + * + * @param aGroup Group to check for non-existence. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkGroupNotExists(String aGroup) throws SQLException { + protected void checkGroupNotExists(String aGroup) throws SQLException { // Empty } - + /** - * Additional check to be implemented by a subclass. - * @param aSize Expected number of groups. + * Additional check to be implemented by a subclass. + * + * @param aSize Expected number of groups. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkGroupCount(int aSize) throws SQLException { + 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(). + * Adds a group and verifies that the group is added using find(), + * list(), and contains(). * + * @throws SQLException DOCUMENT ME! */ - 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 set = groups.list(); - assertEquals(1, set.size()); - assertTrue(set.contains(group)); + 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 set = groups.list(); + assertEquals(1, set.size()); + assertTrue(set.contains(group)); } - + /** * Tries to find a non-existing group. Verifies that null is - * returned. + * returned. * + * @throws SQLException DOCUMENT ME! */ - 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"); + 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. + * Adds duplicate group. Verifies that the existing group is left + * untouched. + * + * @throws SQLException DOCUMENT ME! */ - 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); + 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. + * Removes a group. Verifies that the group is removed and the + * return value is true. * + * @throws SQLException DOCUMENT ME! */ - public void testRemoveGroup() throws SQLException { - Group group1 = new Group("group1"); - groups.add(group1); + 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)); + + 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. + * removed an that the return value is true. * + * @throws SQLException DOCUMENT ME! */ - public void testRemoveNonExistingGroup() throws SQLException { - Group group1 = new Group("group1"); - groups.add(group1); + public void testRemoveNonExistingGroup() throws SQLException { + Group group1 = new Group("group1"); + groups.add(group1); checkGroupCount(1); - Group nonExistingGroup = new Group("group2"); + + Group nonExistingGroup = new Group("group2"); nonExistingGroup.setPrimaryKey(new Long(1000)); nonExistingGroup.setPersistedVersion(1000); assertFalse(groups.remove(nonExistingGroup)); - assertTrue(groups.contains(group1)); + assertTrue(groups.contains(group1)); assertEquals(1, groups.list().size()); - checkGroupCount(1); + checkGroupCount(1); } - + /** - * Adds a number of groups to the set and verifies that list() - * returns them all. + * Adds a number of groups to the set and verifies that list() + * returns them all. * + * @throws SQLException DOCUMENT ME! */ - 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)); + 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 set = groups.list(); - assertTrue(set.contains(group1)); - assertTrue(set.contains(group2)); + + checkGroupExists(group1.getName()); + checkGroupExists(group2.getName()); + checkGroupExists(group3.getName()); + + Set set = groups.list(); + assertTrue(set.contains(group1)); + assertTrue(set.contains(group2)); assertTrue(set.contains(group3)); - - checkGroupCount(3); + + checkGroupCount(3); } } diff --git a/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java b/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java index 76eadebb..4b035819 100644 --- a/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java +++ b/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java @@ -1,309 +1,415 @@ /* * 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; +import java.sql.SQLException; + +import java.util.Set; + + /** * Tests the inmemory user set. Intended to be subclassed for other - * implementations of user set. + * implementations of user set. */ public class InMemoryUserSetTest extends TestCase { - + /** + * DOCUMENT ME! + */ protected static final String PASSWORD = "abc123"; - + + /** + * DOCUMENT ME! + */ private UserSet users; + + /** + * DOCUMENT ME! + */ private GroupSet groups; - - private Group group; - + + /** + * DOCUMENT ME! + */ + private Group group; + /** - * This method must be overriden in subclasses. - * @return New user set object. + * 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()); + 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. + * This method must be overriden in subclasses. + * + * @return New group set object. */ - protected GroupSet createGroupSet() { - return new InMemoryGroupSet(); + protected GroupSet createGroupSet() { + return new InMemoryGroupSet(); } - + /* (non-Javadoc) * @see org.wamblee.test.SpringTestCase#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { super.setUp(); - users = createUserSet(); - groups = createGroupSet(); - group = new Group("group0"); + users = createUserSet(); + groups = createGroupSet(); + group = new Group("group0"); groups.add(group); checkUserCount(0); - } - - protected UserSet getUsers() { - return users; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected UserSet getUsers() { + return users; } - - protected GroupSet getGroups() { - return groups; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected GroupSet getGroups() { + return groups; } - - protected Group createGroup(String aName) { + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Group createGroup(String aName) { return new Group(aName); } - - protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * @param aPassword DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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); + + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + protected void addUserToGroup(User aUser, Group aGroup) + throws UserMgtException { + aUser.addGroup(aGroup); } - - protected void removeUserFromGroup(User aUser, Group aGroup ) throws UserMgtException { - aUser.removeGroup(aGroup); + + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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. + * Additional check to be implemented by a subclass. + * + * @param aUser User to check for existence. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkUserExists(String aUser) throws SQLException { + protected void checkUserExists(String aUser) throws SQLException { // Empty } - + /** - * Additional check to be implemented by a subclass. - * @param aUser User to check for non-existence. + * Additional check to be implemented by a subclass. + * + * @param aUser User to check for non-existence. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkUserNotExists(String aUser) throws SQLException { + protected void checkUserNotExists(String aUser) throws SQLException { // Empty } - + /** - * Additional check to be implemented by a subclass. - * @param aSize Expected number of users. + * Additional check to be implemented by a subclass. + * + * @param aSize Expected number of users. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkUserCount(int aSize) throws SQLException { - assertEquals(aSize, users.size()); + 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. + * Additional check to be implemented by a subclass. + * + * @param aUser User to check for existence. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkGroupExists(String aUser) throws SQLException { + protected void checkGroupExists(String aUser) throws SQLException { // Empty } - + /** - * Additional check to be implemented by a subclass. - * @param aUser User to check for non-existence. + * Additional check to be implemented by a subclass. + * + * @param aUser User to check for non-existence. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkGroupNotExists(String aUser) throws SQLException { + protected void checkGroupNotExists(String aUser) throws SQLException { // Empty } - + /** - * Additional check to be implemented by a subclass. - * @param aSize Expected number of users. + * Additional check to be implemented by a subclass. + * + * @param aSize Expected number of users. + * + * @throws SQLException DOCUMENT ME! */ - protected void checkGroupCount(int aSize) throws SQLException { + protected void checkGroupCount(int aSize) throws SQLException { // Empty } - - + /** - * Adds a user and verifies that the user is added using - * find(), list(), and contains(). + * Adds a user and verifies that the user is added using find(), + * list(), and contains(). * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ - 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 set = users.list(); - assertEquals(1, set.size()); - assertTrue(set.contains(user)); + 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 set = users.list(); + assertEquals(1, set.size()); + assertTrue(set.contains(user)); } - + /** * Tries to find a non-existing user. Verifies that null is - * returned. + * returned. * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ - 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"); + 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. + * Adds duplicate user. Verifies that the existing user is left + * untouched. + * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ - 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); + 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. + * Removes a user. Verifies that the user is removed and the + * return value is true. * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ - public void testRemoveUser() throws SQLException, UserMgtException { - User user1 = createUser("user1", PASSWORD, group); - users.add(user1); + 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)); + + 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. + * Removes a non-existing user. Verifies that no users are removed + * an that the return value is true. * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ - public void testRemoveNonExistingUser() throws SQLException, UserMgtException { - User user1 = createUser("user1", PASSWORD, group); - users.add(user1); + 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)); + assertTrue(users.contains(user1)); assertEquals(1, users.list().size()); - checkUserCount(1); + checkUserCount(1); } - + /** - * Adds a number of users to the set and verifies that list() - * returns them all. + * Adds a number of users to the set and verifies that list() + * returns them all. * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ - 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)); + 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 set = users.list(); - assertTrue(set.contains(user1)); - assertTrue(set.contains(user2)); + + checkUserExists(user1.getName()); + checkUserExists(user2.getName()); + checkUserExists(user3.getName()); + + Set set = users.list(); + assertTrue(set.contains(user1)); + assertTrue(set.contains(user2)); assertTrue(set.contains(user3)); - - checkUserCount(3); + + checkUserCount(3); } - + /** - * Adds several users to different groups and verifies that - * the correct users are returned when looking for users in - * different groups. + * Adds several users to different groups and verifies that the + * correct users are returned when looking for users in different groups. + * * @throws SQLException + * @throws UserMgtException DOCUMENT ME! */ public void testListByGroup() throws SQLException, UserMgtException { - Group group1 = new Group("group1"); + Group group1 = new Group("group1"); Group group2 = new Group("group2"); Group group3 = new Group("group3"); - groups.add(group1); - groups.add(group2); + 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(group2); user1.addGroup(group3); - User user2 = createUser("user2", PASSWORD, group2); - user2.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(user1); + users.add(user2); users.add(user3); - + checkUserExists(user1.getName()); - checkUserExists(user2.getName()); - checkUserExists(user3.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(). - + checkGroupExists(group2.getName()); + checkGroupExists(group3.getName()); + + checkUserCount(3); + checkGroupCount(3 + 1); // also count the group that was created in the setUp(). + Set list = users.list(group1); - assertTrue(list.contains(user1)); + assertTrue(list.contains(user1)); assertEquals(1, list.size()); - - list = users.list(group2); + + list = users.list(group2); assertTrue(list.contains(user1)); assertTrue(list.contains(user2)); assertEquals(2, list.size()); - - list = users.list(group3); + + list = users.list(group3); assertTrue(list.contains(user1)); assertTrue(list.contains(user2)); assertTrue(list.contains(user3)); diff --git a/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java b/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java index bdf4f205..5dde8b9b 100644 --- a/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java +++ b/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java @@ -1,77 +1,126 @@ /* * 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; +import java.util.Set; + + /** * Test of user administration implementation. * * @author Erik Brakkee */ public class UserAdministrationImplTest extends TestCase { + /** + * DOCUMENT ME! + */ + private static final Logger LOGGER = Logger.getLogger(UserAdministrationImplTest.class); - private static final Logger LOGGER = Logger - .getLogger(UserAdministrationImplTest.class); - + /** + * DOCUMENT ME! + */ private static final String USER1 = "piet"; + /** + * DOCUMENT ME! + */ private static final String PASS1 = "passpiet"; + /** + * DOCUMENT ME! + */ private static final String USER2 = "kees"; + /** + * DOCUMENT ME! + */ private static final String PASS2 = "passkees"; + /** + * DOCUMENT ME! + */ private static final String GROUP1 = "cyclists"; + /** + * DOCUMENT ME! + */ private static final String GROUP2 = "runners"; + /** + * DOCUMENT ME! + */ private UserAdministration admin; - /* * (non-Javadoc) - * + * * @see junit.framework.TestCase#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { super.setUp(); admin = createAdmin(); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ protected UserAdministration createAdmin() { - UserSet users = new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"), + 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")); + 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 { + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * @param aPassword DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + protected User createUser(String aName, String aPassword, Group aGroup) + throws UserMgtException { return UsermgtTestUtils.createUser(aName, aPassword, aGroup); } @@ -86,9 +135,10 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Creates a new group. Verifies the group is created correctly and that the - * user is added. - * + * Creates a new group. Verifies the group is created correctly and + * that the user is added. + * + * @throws UserMgtException DOCUMENT ME! */ public void testCreateGroup() throws UserMgtException { Group group = admin.createGroup(GROUP1); @@ -101,21 +151,26 @@ public class UserAdministrationImplTest extends TestCase { assertTrue(groups.contains(group)); } + /** + * DOCUMENT ME! + * + * @param aUsername DOCUMENT ME! + */ private void createInvalidGroup(String aUsername) { try { admin.createGroup(aUsername); fail(); } catch (UserMgtException e) { - assertEquals(UserMgtException.Reason.INVALID_GROUPNAME, e - .getReason()); + 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. - * + * Creates a new group with an invalid name. Verifies that the + * appropriate exception is thrown. + * * @throws UserMgtException */ public void testCreateInvalidGroupName() throws UserMgtException { @@ -127,30 +182,36 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Creates a new group which conflicts with an existing one. Verifies that - * the UserMgtException is thrown and that no group is added. - * + * Creates a new group which conflicts with an existing one. + * Verifies that the UserMgtException is thrown and that no group is + * added. + * + * @throws UserMgtException DOCUMENT ME! */ 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. - * + * Creates a new user. Verifies the user is created correctly and + * that the user is added. + * + * @throws UserMgtException DOCUMENT ME! */ public void testCreateUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + User user = admin.createUser(USER1, PASS1, group); assertNotNull(user); assertEquals(USER1, user.getName()); user.checkPassword(PASS1); @@ -161,21 +222,27 @@ public class UserAdministrationImplTest extends TestCase { assertTrue(users.contains(user)); } + /** + * DOCUMENT ME! + * + * @param aUsername DOCUMENT ME! + * @param aGroup DOCUMENT ME! + */ 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(UserMgtException.Reason.INVALID_USERNAME, e.getReason()); assertEquals(0, admin.getUserCount()); } } /** - * Constructs users with invalid names. Verifies that the appropriate - * exception is thrown. - * + * Constructs users with invalid names. Verifies that the + * appropriate exception is thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testCreateInvalidUserName() throws UserMgtException { Group group = admin.createGroup(GROUP1); @@ -187,13 +254,15 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Creates a new user which conflicts with an existing one. Verifies that - * the UserMgtException is thrown and that no user is added. - * + * Creates a new user which conflicts with an existing one. + * Verifies that the UserMgtException is thrown and that no user is added. + * + * @throws UserMgtException DOCUMENT ME! */ public void testCreateDuplicateUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); admin.createUser(USER1, PASS1, group); + try { admin.createUser(USER1, PASS2, group); fail(); @@ -204,46 +273,50 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Gets a known user by name. Verifies the correct user is obtained. - * Verifies that null is returned when trying to obtain an unknown user. - * + * Gets a known user by name. Verifies the correct user is + * obtained. Verifies that null is returned when trying to obtain an + * unknown user. + * + * @throws UserMgtException DOCUMENT ME! */ public void testGetUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); - User user2 = admin.getUser(USER1); + 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. - * + * Gets a known group by name. Verifies the correct group is + * obtained. Verifies that null is returned when the group is not known. + * + * @throws UserMgtException DOCUMENT ME! */ public void testGetGroup() throws UserMgtException { - Group group = admin.createGroup(GROUP1); + 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. - * + * 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. + * + * @throws UserMgtException DOCUMENT ME! */ public void testAddUserToGroup() throws UserMgtException { - - Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + 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 users = admin.getUsers(group2); assertNotNull(users); assertEquals(1, users.size()); @@ -252,59 +325,73 @@ public class UserAdministrationImplTest extends TestCase { try { admin.addUserToGroup(user, group); } catch (UserMgtException e) { - assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP, e - .getReason()); + 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. - * + * Adds a user to a group where the user does not exist. Verifies + * that an exception occurs. + * + * @throws UserMgtException DOCUMENT ME! */ public void testAddUserToGroupUnknownUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user = createUser(USER1, PASS1, group); + 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. - * + * Adds a user to a group where the user does not exist. Verifies + * that an exception occurs. + * + * @throws UserMgtException DOCUMENT ME! */ public void testAddUserToGroupUnknownGroup() throws UserMgtException { - Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + 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. + * 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. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveUserFromGroup() throws UserMgtException { - Group group = admin.createGroup(GROUP1); + Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + User user = admin.createUser(USER1, PASS1, group); Group group2 = admin.createGroup(GROUP2); admin.addUserToGroup(user, group2); + Set groups = user.getGroups(); assertEquals(2, groups.size()); assertTrue(groups.contains(group)); @@ -318,13 +405,15 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Removes a user from a group where the user is not known. Verifies that an - * exception is thrown. - * + * Removes a user from a group where the user is not known. + * Verifies that an exception is thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveUserFromGroupUnknownUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user = createUser(USER1, GROUP1, group); + User user = createUser(USER1, GROUP1, group); + try { admin.removeUserFromGroup(user, group); } catch (UserMgtException e) { @@ -333,14 +422,16 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Removes a user from a group where the group is not known. Verifies that - * an exception is thrown. - * + * Removes a user from a group where the group is not known. + * Verifies that an exception is thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveUserFromGroupUnknownGroup() throws UserMgtException { - Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + 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) { @@ -349,33 +440,38 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Removes a user from a group where the user is only part of one group. - * Verifies that an exception is thrown. + * Removes a user from a group where the user is only part of one + * group. Verifies that an exception is thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveUserFromGroupOnlyGroup() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + 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()); + 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. - * + * 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. + * + * @throws UserMgtException DOCUMENT ME! */ public void testGetUsersAndGroups() throws UserMgtException { Group group1 = admin.createGroup(GROUP1); Group group2 = admin.createGroup(GROUP2); - User user1 = admin.createUser(USER1, PASS1, group1); + User user1 = admin.createUser(USER1, PASS1, group1); admin.addUserToGroup(user1, group2); - User user2 = admin.createUser(USER2, PASS2, group2); + + User user2 = admin.createUser(USER2, PASS2, group2); Set users = admin.getUsers(); assertEquals(2, users.size()); @@ -403,11 +499,12 @@ public class UserAdministrationImplTest extends TestCase { * 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. - * + * + * @throws UserMgtException DOCUMENT ME! */ public void testRenameUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user1 = admin.createUser(USER1, PASS1, group); + User user1 = admin.createUser(USER1, PASS1, group); admin.renameUser(user1, USER2); assertEquals(USER2, user1.getName()); assertEquals(user1, admin.getUser(USER2)); @@ -423,23 +520,28 @@ public class UserAdministrationImplTest extends TestCase { try { admin.renameUser(user1, user1.getName()); } catch (UserMgtException e2) { - assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2 - .getReason()); + 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. - * + * Renames a user to a user with an invalid username. Verifies that + * the appropriate exception is thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRenameUserInvalidUsername() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user1 = admin.createUser(USER1, PASS1, group); + User user1 = admin.createUser(USER1, PASS1, group); + try { admin.renameUser(user1, USER2); } catch (UserMgtException e) { @@ -448,10 +550,12 @@ public class UserAdministrationImplTest extends TestCase { } /** - * 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. - * + * 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. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRenameGroup() throws UserMgtException { Group group = admin.createGroup(GROUP1); @@ -460,6 +564,7 @@ public class UserAdministrationImplTest extends TestCase { assertEquals(group, admin.getGroup(GROUP2)); admin.createGroup(GROUP1); + try { admin.renameGroup(group, GROUP1); } catch (UserMgtException e) { @@ -469,23 +574,29 @@ public class UserAdministrationImplTest extends TestCase { try { admin.renameGroup(group, group.getName()); } catch (UserMgtException e2) { - assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2 - .getReason()); + 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. - * + * Renames a group to a group with an invalid name. Verifies that + * the appropriate exception is thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRenameGroupInvalidGroupname() throws UserMgtException { Group group = admin.createGroup(GROUP1); + try { admin.renameGroup(group, "a b"); } catch (UserMgtException e) { @@ -494,13 +605,14 @@ public class UserAdministrationImplTest extends TestCase { } /** - * Removes a user. Verifies that the user is removed. Verifies that the an - * exception is thrown when the user does not exist. - * + * Removes a user. Verifies that the user is removed. Verifies that + * the an exception is thrown when the user does not exist. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveUser() throws UserMgtException { Group group = admin.createGroup(GROUP1); - User user = admin.createUser(USER1, PASS1, group); + User user = admin.createUser(USER1, PASS1, group); assertEquals(1, admin.getUserCount()); admin.removeUser(user); @@ -519,10 +631,11 @@ public class UserAdministrationImplTest extends TestCase { } /** - * 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. - * + * 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. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveGroup() throws UserMgtException { Group group1 = admin.createGroup(GROUP1); @@ -532,23 +645,29 @@ public class UserAdministrationImplTest extends TestCase { group1 = admin.createGroup(GROUP1); admin.createUser(USER1, PASS1, group1); + try { admin.removeGroup(group1); } catch (UserMgtException e) { - assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, e - .getReason()); + assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, + e.getReason()); + return; } + fail(); } /** - * Tries to remove an unknown group. Verifies that an exception is thrown. - * + * Tries to remove an unknown group. Verifies that an exception is + * thrown. + * + * @throws UserMgtException DOCUMENT ME! */ public void testRemoveGroupUnknownGroup() throws UserMgtException { - Group group = admin.createGroup(GROUP1); + Group group = admin.createGroup(GROUP1); Group group2 = new Group(GROUP2); + try { admin.removeGroup(group2); } catch (UserMgtException e) { @@ -558,16 +677,17 @@ public class UserAdministrationImplTest extends TestCase { /** * 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 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. @@ -580,24 +700,25 @@ public class UserAdministrationImplTest extends TestCase { user2 = admin.getUser(USER1); user2.checkPassword(PASS2); // this time it should succeed. - } /** * Performance test. Finds a user by name. - * + * + * @throws UserMgtException DOCUMENT ME! */ public void testPerformanceFindUserByName() throws UserMgtException { Group group = admin.createGroup(GROUP1); admin.createUser(USER1, PASS1, group); - int n = 1000; + 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); + + ((float) (System.currentTimeMillis() - time) / 1000.0)); } - } diff --git a/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java b/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java index 07a376c5..f21d670c 100644 --- a/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java +++ b/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java @@ -1,62 +1,137 @@ /* * 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. + * User management test utilities. * * @author Erik Brakkee */ public class UsermgtTestUtils { - + /** + * DOCUMENT ME! + */ private static final String DUMMY_GROUP = "dummygroup"; + + /** + * DOCUMENT ME! + */ private static final String DUMMY_PASSWD = "dummypasswd"; - public static Group createGroup(String aName) { + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public static Group createGroup(String aName) { return new Group(aName); } - - public static User createUser(String aUsername) throws UserMgtException { + + /** + * DOCUMENT ME! + * + * @param aUsername DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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)); + + /** + * DOCUMENT ME! + * + * @param aUsername DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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 { + + /** + * DOCUMENT ME! + * + * @param aUsername DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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()); + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * @param aPassword DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + 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 { + + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + public static void addUserToGroup(User aUser, Group aGroup) + throws UserMgtException { aUser.addGroup(aGroup); } - - public static void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException { + + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * @param aGroup DOCUMENT ME! + * + * @throws UserMgtException DOCUMENT ME! + */ + public static void removeUserFromGroup(User aUser, Group aGroup) + throws UserMgtException { aUser.removeGroup(aGroup); } } diff --git a/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java b/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java index 43bf8c89..4f0cb111 100644 --- a/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java +++ b/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java @@ -1,60 +1,86 @@ /* * 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; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.HashMap; +import java.util.Map; + + /** - * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet} + * 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 = ?"; - + /** + * DOCUMENT ME! + */ + private static final String GROUP_TABLE = "GROUPS"; + + /** + * DOCUMENT ME! + */ + private static final String GROUP_QUERY = "select * from " + GROUP_TABLE + + " where name = ?"; + + /** + * DOCUMENT ME! + */ private DefaultContainer container; + + /** + * DOCUMENT ME! + */ private Scope scope; - + + /** + * DOCUMENT ME! + */ private DatabaseTesterComponent databaseTester; - private GroupSet groupSet; - + + /** + * DOCUMENT ME! + */ + private GroupSet groupSet; + + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { - container = new UserMgtRepositoryTestContainer("top"); - - ObjectConfiguration config = new ObjectConfiguration( - HibernateGroupSetTest.class); - config.getSetterConfig().clear().add( - "setGroupSet").add("setDatabaseTester"); + + ObjectConfiguration config = new ObjectConfiguration(HibernateGroupSetTest.class); + config.getSetterConfig().clear().add("setGroupSet") + .add("setDatabaseTester"); container.addComponent("testcase", this, config); scope = container.start(); @@ -63,16 +89,31 @@ public class HibernateGroupSetTest extends InMemoryGroupSetTest { super.setUp(); } + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override - protected void tearDown() throws Exception { + protected void tearDown() throws Exception { container.stop(scope); - super.tearDown(); + super.tearDown(); } - + + /** + * DOCUMENT ME! + * + * @param aDatabaseTester DOCUMENT ME! + */ public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { databaseTester = aDatabaseTester; } - + + /** + * DOCUMENT ME! + * + * @param aGroupSet DOCUMENT ME! + */ public void setGroupSet(GroupSet aGroupSet) { groupSet = aGroupSet; } @@ -80,53 +121,82 @@ public class HibernateGroupSetTest extends InMemoryGroupSetTest { /* (non-Javadoc) * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int) */ + /** + * DOCUMENT ME! + * + * @param aSize DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @Override protected void checkGroupCount(int aSize) throws SQLException { - databaseTester.flush(); + databaseTester.flush(); super.checkGroupCount(aSize); assertEquals(aSize, databaseTester.getTableSize(GROUP_TABLE)); } - + /* (non-Javadoc) * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @Override - protected void checkGroupExists(final String aGroup) throws SQLException { + protected void checkGroupExists(final String aGroup) + throws SQLException { databaseTester.flush(); - Map 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 res = new HashMap(); - res.put("result", databaseTester.countResultSet(result)); - return res; - } - }); - + + Map 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 res = new HashMap(); + 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) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @Override protected void checkGroupNotExists(String aGroup) throws SQLException { - databaseTester.flush(); - ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup); - assertEquals(0, databaseTester.countResultSet(result)); + databaseTester.flush(); + + ResultSet result = databaseTester.executeQuery(GROUP_QUERY, aGroup); + assertEquals(0, databaseTester.countResultSet(result)); } - + /* (non-Javadoc) * @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected GroupSet createGroupSet() { - return groupSet; + return groupSet; } - } diff --git a/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java b/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java index 08ec4ae9..d62fbdd6 100644 --- a/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java +++ b/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java @@ -1,28 +1,25 @@ /* * 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; @@ -30,109 +27,173 @@ 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; +import java.io.Serializable; + +import java.lang.reflect.Method; + +import java.sql.SQLException; + + /** - * 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. + * 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 { - + /** + * DOCUMENT ME! + */ private static final Log LOG = LogFactory.getLog(HibernateUserAdministrationTest.class); + /** + * DOCUMENT ME! + */ private DefaultContainer container; + + /** + * DOCUMENT ME! + */ private Scope scope; - + + /** + * DOCUMENT ME! + */ private DatabaseTesterComponent databaseTester; + + /** + * DOCUMENT ME! + */ private EhCache userCache; - private UserAdministration userAdmin; - - + + /** + * DOCUMENT ME! + */ + private UserAdministration userAdmin; + /* (non-Javadoc) * @see org.wamblee.usermgt.UserAdministrationImplTest#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @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); + + 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"); + + 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(); } - + + /** + * DOCUMENT ME! + * + * @param aUserCache DOCUMENT ME! + */ public void setUserCache(EhCache aUserCache) { userCache = aUserCache; } - + + /** + * DOCUMENT ME! + * + * @param aDatabaseTester DOCUMENT ME! + */ public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { databaseTester = aDatabaseTester; } - + + /** + * DOCUMENT ME! + * + * @param aUserAdmin DOCUMENT ME! + */ public void setUserAdmin(UserAdministration aUserAdmin) { userAdmin = aUserAdmin; } + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override - protected void tearDown() throws Exception { + protected void tearDown() throws Exception { container.stop(scope); super.tearDown(); } /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.UserAdministrationImplTest#createAdmin() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected UserAdministration createAdmin() { return userAdmin; } + /** + * DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + * @throws RuntimeException DOCUMENT ME! + */ 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"); - } + 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"); + } + } + }); } } } diff --git a/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java b/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java index 46e80fb3..81106a5a 100644 --- a/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java +++ b/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java @@ -1,31 +1,27 @@ /* * 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; @@ -33,69 +29,140 @@ import org.wamblee.usermgt.User; import org.wamblee.usermgt.UserMgtException; import org.wamblee.usermgt.UserSet; +import java.io.Serializable; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Set; + + /** * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet} - * + * * @author Erik Brakkee */ public class HibernateUserSetTest extends InMemoryUserSetTest { - + /** + * DOCUMENT ME! + */ private static final String USER_TABLE = "USERS"; + + /** + * DOCUMENT ME! + */ private static final String GROUP_TABLE = "GROUPS"; + /** + * DOCUMENT ME! + */ private static final String USER_QUERY = "select * from " + USER_TABLE - + " where name = ?"; + + " where name = ?"; + + /** + * DOCUMENT ME! + */ private static final String GROUP_QUERY = "select * from " + GROUP_TABLE - + " where name = ?"; + + " where name = ?"; + /** + * DOCUMENT ME! + */ private DefaultContainer container; + + /** + * DOCUMENT ME! + */ private Scope scope; - + + /** + * DOCUMENT ME! + */ private UserSet userset; + + /** + * DOCUMENT ME! + */ private GroupSet groupset; + + /** + * DOCUMENT ME! + */ private EhCache userCache; + + /** + * DOCUMENT ME! + */ private DatabaseTesterComponent databaseTester; /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.InMemoryUserSetTest#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @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"); + + 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(); } + /** + * DOCUMENT ME! + * + * @param aUserset DOCUMENT ME! + */ public void setUserset(UserSet aUserset) { userset = aUserset; } + /** + * DOCUMENT ME! + * + * @param aGroupset DOCUMENT ME! + */ public void setGroupset(GroupSet aGroupset) { groupset = aGroupset; } + /** + * DOCUMENT ME! + * + * @param aUserCache DOCUMENT ME! + */ public void setUserCache(EhCache aUserCache) { userCache = aUserCache; } + /** + * DOCUMENT ME! + * + * @param aDatabaseTester DOCUMENT ME! + */ public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { databaseTester = aDatabaseTester; } + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void tearDown() throws Exception { container.stop(scope); @@ -111,9 +178,16 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int) */ + /** + * DOCUMENT ME! + * + * @param aSize DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @Override protected void checkUserCount(int aSize) throws SQLException { databaseTester.flush(); @@ -123,33 +197,56 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @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) */ + /** + * DOCUMENT ME! + * + * @param aUser DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @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) */ + /** + * DOCUMENT ME! + * + * @param aSize DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @Override protected void checkGroupCount(int aSize) throws SQLException { databaseTester.flush(); @@ -158,9 +255,16 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @Override protected void checkGroupExists(String aGroup) throws SQLException { databaseTester.flush(); @@ -171,21 +275,34 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aGroup DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ @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() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected UserSet createUserSet() { return userset; @@ -193,23 +310,33 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { /* * (non-Javadoc) - * + * * @see org.wamblee.usermgt.InMemoryUserSetTest#createGroupSet() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @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. + * 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. + * + * @throws SQLException DOCUMENT ME! + * @throws UserMgtException DOCUMENT ME! */ 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); @@ -224,7 +351,8 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { addUserToGroup(user, group2); getUsers().userModified(user); clearUserCache(); - User user2 = getUsers().find("user"); + + User user2 = getUsers().find("user"); Set userGroups = user2.getGroups(); assertTrue(user2.isInGroup("group1")); assertTrue(user2.isInGroup("group2")); @@ -233,11 +361,10 @@ public class HibernateUserSetTest extends InMemoryUserSetTest { removeUserFromGroup(user, group1); getUsers().userModified(user); clearUserCache(); - user2 = getUsers().find("user"); - userGroups = user2.getGroups(); + user2 = getUsers().find("user"); + userGroups = user2.getGroups(); assertFalse(user2.isInGroup("group1")); assertTrue(user2.isInGroup("group2")); assertEquals(1, userGroups.size()); } - } diff --git a/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java b/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java index dd443916..cac803d2 100644 --- a/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java +++ b/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,8 +15,6 @@ */ 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; @@ -24,30 +22,40 @@ 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; +import java.io.IOException; + + /** - * * Test container for repository tests of user management. - * + * * @author Erik Brakkee */ public class UserMgtRepositoryTestContainer extends DefaultContainer { - - public UserMgtRepositoryTestContainer(String aName) throws IOException { +/** + * Creates a new UserMgtRepositoryTestContainer object. + * + * @param aName DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + public UserMgtRepositoryTestContainer(String aName) + throws IOException { super(aName); DatabaseComponentFactory.addDatabaseConfig(this); addComponent(new DatasourceComponent("datasource")); - - ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); + + ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); mappingFilesConfig.getSetterConfig().initAllSetters(); - addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig); + addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), + mappingFilesConfig); addComponent(new HibernateComponent("hibernate")); addComponent(new UserGroupRepositoryComponent("usersgroups")); - ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class); + + ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class); dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters(); addComponent("databaseTester", dbtesterConfig); - } - } diff --git a/support/general/src/main/java/org/wamblee/cache/Cache.java b/support/general/src/main/java/org/wamblee/cache/Cache.java index 15f2c508..92df65ec 100644 --- a/support/general/src/main/java/org/wamblee/cache/Cache.java +++ b/support/general/src/main/java/org/wamblee/cache/Cache.java @@ -1,55 +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.cache; import java.io.Serializable; + /** - * The Cache interface represents... a cache. - * In some circumstances it is more optimal to implement caching directly in + * The Cache 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. + * from the used cache implementation. + * Cache implementations must be thread-safe. */ public interface Cache { - /** - * Adds a key-value pair to the cache. - * @param aKey Key. - * @param aValue Value. + * Adds a key-value pair to the cache. + * + * @param aKey Key. + * @param aValue Value. */ - void put(KeyType aKey, ValueType aValue); - + void put(KeyType aKey, ValueType aValue); + /** - * Retrieves a value from the cache. - * @param aKey Key to retrieve. - * @return Key. + * 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. + * Removes an entry from the cache. + * + * @param aKey Key to remove the entry for. */ - void remove(KeyType aKey); - + void remove(KeyType aKey); + /** - * Removes all entries from the cache. - * + * Removes all entries from the cache. */ - void clear(); + void clear(); } diff --git a/support/general/src/main/java/org/wamblee/cache/CachedObject.java b/support/general/src/main/java/org/wamblee/cache/CachedObject.java index f844c728..bdabd517 100644 --- a/support/general/src/main/java/org/wamblee/cache/CachedObject.java +++ b/support/general/src/main/java/org/wamblee/cache/CachedObject.java @@ -1,52 +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.cache; +import org.apache.log4j.Logger; + 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). + * 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 + * + * @param DOCUMENT ME! + * @param DOCUMENT ME! */ public class CachedObject { - - private static final Logger LOGGER = Logger.getLogger(CachedObject.class); - /** - * Callback invoked to compute an object if it was not found in the cache. - * - * @param - * Type of the object + * DOCUMENT ME! */ - public static interface Computation { - /** - * 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); - } + private static final Logger LOGGER = Logger.getLogger(CachedObject.class); /** * Cache to use. @@ -59,13 +47,14 @@ public class CachedObject computation; - /** +/** * Constructs the cached object. - * + * * @param aCache * Cache to use. * @param aObjectKey @@ -75,22 +64,23 @@ public class CachedObject aCache, KeyType aObjectKey, - Computation aComputation) { - cache = aCache; - objectKey = aObjectKey; - computation = aComputation; + Computation aComputation) { + cache = aCache; + objectKey = aObjectKey; + computation = aComputation; } /** - * Gets the object. Since the object is cached, different calls to this - * method may return different objects. - * + * 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. + // cache is + // thread safe. + if (object == null) { // synchronize the computation to make sure that the object is only // computed @@ -99,6 +89,7 @@ public class CachedObject + * Type of the object + */ + public static interface Computation { + /** + * 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); + } } diff --git a/support/general/src/main/java/org/wamblee/cache/EhCache.java b/support/general/src/main/java/org/wamblee/cache/EhCache.java index 1d9da8a2..dd01cd94 100644 --- a/support/general/src/main/java/org/wamblee/cache/EhCache.java +++ b/support/general/src/main/java/org/wamblee/cache/EhCache.java @@ -1,41 +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.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; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; + + /** * Cache implemented on top of EhCache. * * @author Erik Brakkee + * + * @param DOCUMENT ME! + * @param DOCUMENT ME! */ public class EhCache - implements org.wamblee.cache.Cache { - + implements org.wamblee.cache.Cache { + /** + * DOCUMENT ME! + */ private static final Logger LOGGER = Logger.getLogger(EhCache.class); /** @@ -48,9 +54,9 @@ public class EhCache DOCUMENT ME! + * @param DOCUMENT ME! */ public class ForeverCache - implements Cache { - + implements Cache { /** * Cached entries. */ private HashMap map; - /** +/** * Constructs the cache. - * + * */ public ForeverCache() { map = new HashMap(); @@ -43,36 +46,57 @@ public class ForeverCache DOCUMENT ME! + * @param DOCUMENT ME! */ -public class ZeroCache - implements Cache { - - public ZeroCache() { +public class ZeroCache + implements Cache { + /** + * Creates a new ZeroCache object. + */ + public ZeroCache() { // Empty. } - + /* (non-Javadoc) * @see org.wamblee.cache.Cache#put(KeyType, ValueType) */ + /** + * DOCUMENT ME! + * + * @param aKey DOCUMENT ME! + * @param aValue DOCUMENT ME! + */ public void put(KeyType aKey, ValueType aValue) { // Empty. } - + /* (non-Javadoc) * @see org.wamblee.cache.Cache#get(KeyType) */ + /** + * DOCUMENT ME! + * + * @param aKey DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public ValueType get(KeyType aKey) { return null; } - + /* (non-Javadoc) * @see org.wamblee.cache.Cache#remove(KeyType) */ + /** + * DOCUMENT ME! + * + * @param aKey DOCUMENT ME! + */ public void remove(KeyType aKey) { // Empty } - + /* (non-Javadoc) * @see org.wamblee.cache.Cache#clear() */ + /** + * DOCUMENT ME! + */ public void clear() { // Empty } diff --git a/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java b/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java index 75cdcb1e..296049fd 100644 --- a/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java +++ b/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java @@ -1,40 +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.collections; +import org.wamblee.conditions.Condition; + import java.util.Collection; -import org.wamblee.conditions.Condition; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class CollectionFilter { - /** - * Filters a collection by adding all elements in the from collection - * that satisfy a given condition to the to collection. - * @param 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. + * Filters a collection by adding all elements in the from + * collection that satisfy a given condition to the to collection. + * + * @param 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 void filter(Collection aFrom, Collection aTo, Condition aCondition) { - for (T t: aFrom) { - if ( aCondition.matches(t)) { - aTo.add(t); - } - } - } - + public static void filter(Collection aFrom, Collection aTo, + Condition aCondition) { + for (T t : aFrom) { + if (aCondition.matches(t)) { + aTo.add(t); + } + } + } } diff --git a/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java b/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java index 8b25bbb6..61949d78 100644 --- a/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java +++ b/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java @@ -1,40 +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.concurrency; import java.util.concurrent.locks.ReentrantLock; + /** - * In memory JVM lock. + * In memory JVM lock. * * @author Erik Brakkee - */ + */ public class JvmLock implements Lock { - /** - * Reentrant lock to use. + * Reentrant lock to use. */ - private ReentrantLock lock; - + private ReentrantLock lock; + /** - * In-memory lock. + * In-memory lock. */ - public JvmLock() { - lock = new ReentrantLock(true); + public JvmLock() { + lock = new ReentrantLock(true); } /* (non-Javadoc) @@ -43,11 +42,11 @@ public class JvmLock implements Lock { public void acquire() { lock.lock(); } - + /* (non-Javadoc) * @see org.wamblee.concurrency.Lock#release() */ public void release() { - lock.unlock(); + lock.unlock(); } } diff --git a/support/general/src/main/java/org/wamblee/concurrency/Lock.java b/support/general/src/main/java/org/wamblee/concurrency/Lock.java index 50cc7842..a942c97f 100644 --- a/support/general/src/main/java/org/wamblee/concurrency/Lock.java +++ b/support/general/src/main/java/org/wamblee/concurrency/Lock.java @@ -1,37 +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.concurrency; + /** - * Represents a re-entrant lock. - * Implementations can provide inmemory JVM locking or full cluster safe locking - * mechanisms. + * 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. + * Acquires the lock. */ - void acquire(); - + void acquire(); + /** - * Releases the lock. + * Releases the lock. */ - void release(); + void release(); } diff --git a/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java b/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java index bfa4d311..678801d5 100644 --- a/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java +++ b/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java @@ -1,18 +1,18 @@ /* * 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; @@ -43,8 +43,8 @@ public class ReadWriteLock { * Constructs read-write lock. */ public ReadWriteLock() { - readers = new HashSet(); - writer = null; + readers = new HashSet(); + writer = null; } /** @@ -57,14 +57,14 @@ public class ReadWriteLock { public synchronized void acquireRead() { if (readers.contains(Thread.currentThread())) { throw new IllegalStateException( - "Read lock already acquired by current thread: " - + Thread.currentThread()); + "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()); + "Trying to acquire the read lock while already holding a write lock: " + + Thread.currentThread()); } while (writer != null) { @@ -106,14 +106,14 @@ public class ReadWriteLock { 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()); + "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()); + "Trying to acquire a write lock while already holding the read lock: " + + Thread.currentThread()); } // wait until there are no more writers and no more diff --git a/support/general/src/main/java/org/wamblee/conditions/AndCondition.java b/support/general/src/main/java/org/wamblee/conditions/AndCondition.java index 52b53950..8ef909b5 100644 --- a/support/general/src/main/java/org/wamblee/conditions/AndCondition.java +++ b/support/general/src/main/java/org/wamblee/conditions/AndCondition.java @@ -1,36 +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.conditions; import java.util.ArrayList; import java.util.List; + /** * Represents a logical and of different boolean conditions. * * @author Erik Brakkee + * + * @param DOCUMENT ME! */ public class AndCondition implements Condition { - + /** + * DOCUMENT ME! + */ private List> conditions; - /** +/** * Constructs the condition. - * + * * @param aCondition1 * First condition. * @param aCondition2 @@ -42,9 +46,9 @@ public class AndCondition implements Condition { conditions.add(aCondition2); } - /** +/** * Constructs the and condition. - * + * * @param aConditions * List of conditions to use in the logical and. */ @@ -54,16 +58,23 @@ public class AndCondition implements Condition { /* * (non-Javadoc) - * + * * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program) */ + /** + * DOCUMENT ME! + * + * @param aObject DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean matches(T aObject) { for (Condition condition : conditions) { if (!condition.matches(aObject)) { return false; } } + return true; } - } diff --git a/support/general/src/main/java/org/wamblee/conditions/Condition.java b/support/general/src/main/java/org/wamblee/conditions/Condition.java index bf4c217a..8b410f74 100644 --- a/support/general/src/main/java/org/wamblee/conditions/Condition.java +++ b/support/general/src/main/java/org/wamblee/conditions/Condition.java @@ -1,33 +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.conditions; - /** * Determines if an object matches a certain condition. * * @author Erik Brakkee */ public interface Condition { - /** - * Determines if an object matches a condition. - * @param aObject object to match. - * @return True iff the object matches. + * Determines if an object matches a condition. + * + * @param aObject object to match. + * + * @return True iff the object matches. */ - boolean matches(T aObject); + boolean matches(T aObject); } diff --git a/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java b/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java index d9848d7c..1c64974c 100644 --- a/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java +++ b/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java @@ -1,43 +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.conditions; /** - * Condition which always returns a fixed value. + * Condition which always returns a fixed value. * * @author Erik Brakkee + * + * @param DOCUMENT ME! */ public class FixedCondition implements Condition { - - private boolean value; - /** - * Constructs the condition. - * @param aValue Fixed value of the condition. + * DOCUMENT ME! */ - public FixedCondition(boolean aValue) { - value = aValue; + 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) */ + /** + * DOCUMENT ME! + * + * @param aObject DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean matches(T aObject) { - return value; + return value; } - } diff --git a/support/general/src/main/java/org/wamblee/conditions/OrCondition.java b/support/general/src/main/java/org/wamblee/conditions/OrCondition.java index a15b4eff..77b80324 100644 --- a/support/general/src/main/java/org/wamblee/conditions/OrCondition.java +++ b/support/general/src/main/java/org/wamblee/conditions/OrCondition.java @@ -1,36 +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.conditions; import java.util.ArrayList; import java.util.List; + /** * Represents a logical or of different boolean conditions. * * @author Erik Brakkee + * + * @param DOCUMENT ME! */ public class OrCondition implements Condition { - + /** + * DOCUMENT ME! + */ private List> conditions; - /** +/** * Constructs the condition. - * + * * @param aCondition1 * First condition. * @param aCondition2 @@ -42,9 +46,9 @@ public class OrCondition implements Condition { conditions.add(aCondition2); } - /** +/** * Constructs the or condition. - * + * * @param aConditions * List of conditions to use in the logical or. */ @@ -54,16 +58,23 @@ public class OrCondition implements Condition { /* * (non-Javadoc) - * + * * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program) */ + /** + * DOCUMENT ME! + * + * @param aObject DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean matches(T aObject) { for (Condition condition : conditions) { if (condition.matches(aObject)) { return true; } } + return false; } - } diff --git a/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java b/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java index cfc1e165..3aa68b14 100644 --- a/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java +++ b/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java @@ -1,73 +1,87 @@ /* * 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 org.apache.commons.beanutils.PropertyUtils; + 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 + * Condition to check whether a given property value matches a certain * regular expression. * * @author Erik Brakkee + * + * @param DOCUMENT ME! */ public class PropertyRegexCondition implements Condition { - /** - * Property name. + * Property name. */ private String property; - + /** - * Regular expression. + * Regular expression. */ private Pattern regex; - + /** - * Whether or not to convert the value to lowercase before matching. + * 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. + 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; + 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) */ + /** + * DOCUMENT ME! + * + * @param aObject DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean matches(T aObject) { try { String value = PropertyUtils.getProperty(aObject, property) + ""; - if ( tolower ) { - value = value.toLowerCase(); + + if (tolower) { + value = value.toLowerCase(); } - Matcher matcher = regex.matcher(value); - return matcher.matches(); + + Matcher matcher = regex.matcher(value); + + return matcher.matches(); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvocationTargetException e) { diff --git a/support/general/src/main/java/org/wamblee/general/BeanFactory.java b/support/general/src/main/java/org/wamblee/general/BeanFactory.java index 56844bd7..9406b297 100644 --- a/support/general/src/main/java/org/wamblee/general/BeanFactory.java +++ b/support/general/src/main/java/org/wamblee/general/BeanFactory.java @@ -1,55 +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.general; + /** - * Bean factory used to obtain objects in a transparent way. + * 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. + * 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. */ - T find(Class aClass); - - /** - * Finds a bean with the given id which can be cast to the specified - * class. - * @param 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 find(String aId, Class aClass); + Object find(String aId); + + T find(Class aClass); + + T find(String aId, Class aClass); } diff --git a/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java b/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java index 9110db9b..d29fc3e2 100644 --- a/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java +++ b/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java @@ -1,38 +1,41 @@ /* * 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. + * Exception thrown by the BeanFactory if an object could not be found. * * @author Erik Brakkee */ public class BeanFactoryException extends RuntimeException { + /** + * DOCUMENT ME! + */ static final long serialVersionUID = -1215992188624874902L; - /** - * Constructs the exception. - * @param aMsg Message. +/** + * Constructs the exception. + * @param aMsg Message. */ - public BeanFactoryException(String aMsg) { - super(aMsg); + public BeanFactoryException(String aMsg) { + super(aMsg); } - - /** - * Constructs the exception. + +/** + * Constructs the exception. * @param aMsg Message. * @param aThrowable Cause of the exception. */ diff --git a/support/general/src/main/java/org/wamblee/general/BeanKernel.java b/support/general/src/main/java/org/wamblee/general/BeanKernel.java index d05eef3d..36d2e9b2 100644 --- a/support/general/src/main/java/org/wamblee/general/BeanKernel.java +++ b/support/general/src/main/java/org/wamblee/general/BeanKernel.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,24 +15,29 @@ */ 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; +import java.io.IOException; +import java.io.InputStream; + +import java.util.Properties; + + /** * 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. + * 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 { - + /** + * DOCUMENT ME! + */ private static final Log LOG = LogFactory.getLog(BeanKernel.class); /** @@ -41,8 +46,8 @@ public final class BeanKernel { 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. + * 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"; @@ -51,20 +56,19 @@ public final class BeanKernel { */ 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. + * 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; @@ -72,7 +76,7 @@ public final class BeanKernel { /** * Gets the bean factory. - * + * * @return Bean factory. */ public static BeanFactory getBeanFactory() { @@ -81,32 +85,40 @@ public final class BeanKernel { BEAN_FACTORY = lookupBeanFactory(BEAN_KERNEL_PROP_FILE); } } + return BEAN_FACTORY; } /** * Lookup the bean factory based on the properties file. - * + * + * @param aPropertyFilename DOCUMENT ME! + * * @return Bean factory. + * + * @throws BeanFactoryException DOCUMENT ME! */ static BeanFactory lookupBeanFactory(String aPropertyFilename) { InputResource resource = new ClassPathResource(aPropertyFilename); - InputStream is; + InputStream is; + try { - is = resource.getInputStream(); + is = resource.getInputStream(); } catch (IOException e) { - throw new BeanFactoryException("Cannot open resource " + resource, - 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); + + 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); + + resource, e); } finally { try { is.close(); diff --git a/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java b/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java index 5275e159..b3453a9a 100644 --- a/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java +++ b/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java @@ -1,53 +1,55 @@ /* * 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.io.IOException; + import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; + + /** * Utility for working with the class loader. Based on the ClassPathHacker - * example found on the internet. + * 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. + * Adds all jars in the given directory to the class path. + * @param aDirectory Directory. * @throws IOException */ - public static void addJarsInDirectory(File aDirectory) 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() + "'"); + System.out.println("Considering '" + aFile.getCanonicalPath() + + "'"); + if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) { - System.out.println("Adding '" + aFile.getCanonicalPath() - + "' to classpath."); + System.out.println("Adding '" + aFile.getCanonicalPath() + + "' to classpath."); addFile(aFile); } } @@ -55,7 +57,7 @@ public class ClassLoaderUtils { /** * Adds a file to the classpath. - * @param aFilename Filename to add. + * @param aFilename Filename to add. * @throws IOException */ public static void addFile(String aFilename) throws IOException { @@ -64,8 +66,8 @@ public class ClassLoaderUtils { } /** - * Adds a file to the classpath. - * @param aFile File to add. + * Adds a file to the classpath. + * @param aFile File to add. * @throws IOException */ public static void addFile(File aFile) throws IOException { @@ -74,25 +76,22 @@ public class ClassLoaderUtils { /** * Adds a url to the classpath. - * @param aUrl Url to add. + * @param aUrl Url to add. * @throws IOException */ public static void addURL(URL aUrl) throws IOException { - - URLClassLoader sysloader = (URLClassLoader) ClassLoader - .getSystemClassLoader(); + URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { - Method method = sysclass.getDeclaredMethod("addURL", new Class[]{ URL.class } ); + 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"); + "Error, could not add URL to system classloader"); } - } - } diff --git a/support/general/src/main/java/org/wamblee/general/Pair.java b/support/general/src/main/java/org/wamblee/general/Pair.java index bf5e589c..e041729b 100644 --- a/support/general/src/main/java/org/wamblee/general/Pair.java +++ b/support/general/src/main/java/org/wamblee/general/Pair.java @@ -1,15 +1,12 @@ - - - /* * 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. @@ -18,10 +15,11 @@ */ package org.wamblee.general; + /** * Represents a pair of objects. This is inspired on the C++ Standard Template * Library pair template. - * + * * @param * Type of the first object. * @param @@ -30,14 +28,12 @@ package org.wamblee.general; * @author Erik Brakkee */ public class Pair { - private T t; - private U u; /** * Constructs the pair. - * + * * @param aT * First object. * @param aU @@ -50,7 +46,7 @@ public class Pair { /** * Copies a pair. - * + * * @param aPair * Pair to copy. */ @@ -61,7 +57,7 @@ public class Pair { /** * Gets the first object of the pair. - * + * * @return First object. */ public T getFirst() { @@ -70,11 +66,10 @@ public class Pair { /** * Gets the second object of the pair. - * + * * @return Second object. */ public U getSecond() { return u; } - } diff --git a/support/general/src/main/java/org/wamblee/io/ClassPathResource.java b/support/general/src/main/java/org/wamblee/io/ClassPathResource.java index 7ecdcc97..28fe9094 100644 --- a/support/general/src/main/java/org/wamblee/io/ClassPathResource.java +++ b/support/general/src/main/java/org/wamblee/io/ClassPathResource.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,6 +18,7 @@ package org.wamblee.io; import java.io.IOException; import java.io.InputStream; + /** * Represents an input resource in the classpath. */ @@ -27,9 +28,9 @@ public class ClassPathResource implements InputResource { */ private String resource; - /** +/** * Construct the class path resource. - * + * * @param aResource * Resource */ @@ -39,24 +40,38 @@ public class ClassPathResource implements InputResource { /* * (non-Javadoc) - * + * * @see org.wamblee.io.InputResource#getInputStream() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public InputStream getInputStream() throws IOException { InputStream stream = Thread.currentThread().getContextClassLoader() - .getResourceAsStream(resource); + .getResourceAsStream(resource); + if (stream == null) { throw new IOException("Class path resource '" + resource - + "' not found."); + + "' not found."); } + return stream; } /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public String toString() { return "ClassPathResource(" + resource + ")"; } diff --git a/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java b/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java index 3f5488b0..b777a97c 100644 --- a/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java +++ b/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java @@ -1,108 +1,139 @@ /* * 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 org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + 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 { + /** + * DOCUMENT ME! + */ + private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class); + + /** + * DOCUMENT ME! + */ + private File directory; + + /** + * DOCUMENT ME! + */ + private FileFilter filter; + + /** + * DOCUMENT ME! + */ + private Listener listener; + + /** + * DOCUMENT ME! + */ + private Map contents; + +/** + * Creates a new DirectoryMonitor object. + * + * @param aDirectory DOCUMENT ME! + * @param aFilefilter DOCUMENT ME! + * @param aListener DOCUMENT ME! + */ + 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(); + } + + /** + * 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 newContents = new HashMap(); + File[] files = directory.listFiles(filter); + + // Check deleted files. + Set deletedFiles = new HashSet(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; + } + + public static interface Listener { + void fileChanged(File aFile); - 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 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(); - } - - /** - * 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 newContents = new HashMap(); - File[] files = directory.listFiles(filter); - - // Check deleted files. - Set deletedFiles = new HashSet(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; - } + void fileCreated(File aFile); + void fileDeleted(File aFile); + } } diff --git a/support/general/src/main/java/org/wamblee/io/FileResource.java b/support/general/src/main/java/org/wamblee/io/FileResource.java index fd64001a..58c88b82 100644 --- a/support/general/src/main/java/org/wamblee/io/FileResource.java +++ b/support/general/src/main/java/org/wamblee/io/FileResource.java @@ -1,12 +1,12 @@ /* * 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. @@ -21,6 +21,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; + /** * Resource implemention for reading from a file. * @@ -32,9 +33,9 @@ public class FileResource implements InputResource { */ private File file; - /** +/** * Constructs the resource. - * + * * @param aFile * File to read. */ @@ -44,9 +45,16 @@ public class FileResource implements InputResource { /* * (non-Javadoc) - * + * * @see org.wamblee.io.InputResource#getInputStream() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public InputStream getInputStream() throws IOException { return new BufferedInputStream(new FileInputStream(file)); } diff --git a/support/general/src/main/java/org/wamblee/io/InputResource.java b/support/general/src/main/java/org/wamblee/io/InputResource.java index 2a0e8cda..ab9cb2a2 100644 --- a/support/general/src/main/java/org/wamblee/io/InputResource.java +++ b/support/general/src/main/java/org/wamblee/io/InputResource.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,6 +18,7 @@ package org.wamblee.io; import java.io.IOException; import java.io.InputStream; + /** * Represents a resource from which information can be read. * @@ -25,12 +26,12 @@ import java.io.InputStream; */ public interface InputResource { /** - * Gets the input stream to the resource. The obtained input stream must be - * closed once reading has finished. - * + * 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. + * + * @throws IOException in case the resource cannot be found. */ InputStream getInputStream() throws IOException; } diff --git a/support/general/src/main/java/org/wamblee/io/SimpleProcess.java b/support/general/src/main/java/org/wamblee/io/SimpleProcess.java index 74438644..3e0e7f85 100644 --- a/support/general/src/main/java/org/wamblee/io/SimpleProcess.java +++ b/support/general/src/main/java/org/wamblee/io/SimpleProcess.java @@ -1,20 +1,23 @@ /* * 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 org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -25,144 +28,211 @@ import java.io.PrintStream; import java.io.StringWriter; import java.io.Writer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class SimpleProcess { + /** + * DOCUMENT ME! + */ + private static final Log LOG = LogFactory.getLog(SimpleProcess.class); - private static final Log LOG = LogFactory.getLog(SimpleProcess.class); + /** + * DOCUMENT ME! + */ + private File directory; + + /** + * DOCUMENT ME! + */ + private String[] cmd; - private File directory; + /** + * DOCUMENT ME! + */ + private String stdout; - private String[] cmd; - - private String stdout; - private String stderr; + /** + * DOCUMENT ME! + */ + private String stderr; - public SimpleProcess(File aDirectory, String[] aCmd) { - directory = aDirectory; - cmd = aCmd; - } +/** + * Creates a new SimpleProcess object. + * + * @param aDirectory DOCUMENT ME! + * @param aCmd DOCUMENT ME! + */ + public SimpleProcess(File aDirectory, String[] aCmd) { + directory = aDirectory; + cmd = aCmd; + } /** + * DOCUMENT ME! + * * @return the stdout */ public String getStdout() { return stdout; } - + /** + * DOCUMENT ME! + * * @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 myStdout = new StringWriter(); - StringWriter myStderr = new StringWriter(); - Thread stdoutReader = readAndLogStream("STDOUT> ", proc - .getInputStream(), myStdout); - Thread stderrReader = readAndLogStream("STDERR> ", proc - .getErrorStream(), myStderr); - - try { - proc.waitFor(); - } catch (InterruptedException e) { - IOException exception = new IOException( - "Process was terminated: " + this); - exception.initCause(e); - throw exception; - } - waitForReader(stdoutReader); - waitForReader(stderrReader); - - stdout = myStdout.toString(); - stderr = myStderr.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() { + + /** + * 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(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + 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 myStdout = new StringWriter(); + StringWriter myStderr = new StringWriter(); + Thread stdoutReader = readAndLogStream("STDOUT> ", + proc.getInputStream(), myStdout); + Thread stderrReader = readAndLogStream("STDERR> ", + proc.getErrorStream(), myStderr); + + try { + proc.waitFor(); + } catch (InterruptedException e) { + IOException exception = new IOException( + "Process was terminated: " + this); + exception.initCause(e); + throw exception; + } + + waitForReader(stdoutReader); + waitForReader(stderrReader); + + stdout = myStdout.toString(); + stderr = myStderr.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; + } + } + + /** + * DOCUMENT ME! + * + * @param aReaderThread DOCUMENT ME! + */ + private void waitForReader(Thread aReaderThread) { + try { + aReaderThread.join(); + } catch (InterruptedException e) { + LOG.warn(this + + ": error waiting for output stream reader of process to finish"); + } + } + + /** + * DOCUMENT ME! + * + * @param aPrefix DOCUMENT ME! + * @param aStream DOCUMENT ME! + * @param aOutput DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String toString() { String fullcmd = ""; - for (String part: cmd) { - fullcmd += part + " "; + + for (String part : cmd) { + fullcmd += (part + " "); } - return "process(dir = '" + directory + "', cmd = '" + fullcmd + "')"; - } + + return "process(dir = '" + directory + "', cmd = '" + fullcmd + "')"; + } } diff --git a/support/general/src/main/java/org/wamblee/io/StreamResource.java b/support/general/src/main/java/org/wamblee/io/StreamResource.java index 7df7ba20..2d2f7a78 100644 --- a/support/general/src/main/java/org/wamblee/io/StreamResource.java +++ b/support/general/src/main/java/org/wamblee/io/StreamResource.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,6 +18,7 @@ package org.wamblee.io; import java.io.IOException; import java.io.InputStream; + /** * Input resource based on an input stream. * @@ -29,9 +30,9 @@ public class StreamResource implements InputResource { */ private InputStream stream; - /** +/** * Constructs a resource. - * + * * @param aStream * Input stream to read. */ @@ -41,9 +42,16 @@ public class StreamResource implements InputResource { /* * (non-Javadoc) - * + * * @see InputResource#getInputStream() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public InputStream getInputStream() throws IOException { return stream; } diff --git a/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java b/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java index 0b14585c..8239ed11 100644 --- a/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java +++ b/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java @@ -1,21 +1,21 @@ /* * 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)} @@ -23,12 +23,11 @@ package org.wamblee.observer; * * @author Erik Brakkee */ -public class DefaultObserverNotifier implements - ObserverNotifier { - +public class DefaultObserverNotifier + implements ObserverNotifier { /** * Constructs the notifier. - * + * */ public DefaultObserverNotifier() { // Empty @@ -36,12 +35,12 @@ public class DefaultObserverNotifier implements /* * (non-Javadoc) - * + * * @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer, * ObservableType, Event) */ public void update(Observer aObserver, - ObservableType aObservable, Event aEvent) { + ObservableType aObservable, Event aEvent) { aObserver.send(aObservable, aEvent); } } diff --git a/support/general/src/main/java/org/wamblee/observer/Observable.java b/support/general/src/main/java/org/wamblee/observer/Observable.java index 820db38c..096b0600 100644 --- a/support/general/src/main/java/org/wamblee/observer/Observable.java +++ b/support/general/src/main/java/org/wamblee/observer/Observable.java @@ -1,34 +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.observer; -import java.util.List; +import org.apache.log4j.Logger; + import java.util.ArrayList; +import java.util.List; 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 { - private static final Logger LOGGER = Logger.getLogger(Observable.class); /** @@ -53,14 +52,14 @@ public class Observable { /** * 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 aNotifier) { + ObserverNotifier aNotifier) { observable = aObservable; notifier = aNotifier; observers = new TreeMap>(); @@ -69,21 +68,24 @@ public class Observable { /** * Subscribe an obvers. - * + * * @param aObserver * Observer to subscribe. * @return Event Event to send. */ - public synchronized long subscribe(Observer aObserver) { + public synchronized long subscribe( + Observer aObserver) { long subscription = counter++; // integer rage is so large it will - // never roll over. + // never roll over. + observers.put(subscription, aObserver); + return subscription; } /** * Unsubscribe an observer. - * + * * @param aSubscription * Subscription which is used * @throws IllegalArgumentException @@ -91,15 +93,16 @@ public class Observable { */ public synchronized void unsubscribe(long aSubscription) { Object obj = observers.remove(aSubscription); + if (obj == null) { - throw new IllegalArgumentException("Subscription '" + aSubscription - + "'"); + throw new IllegalArgumentException("Subscription '" + + aSubscription + "'"); } } /** * Gets the number of subscribed observers. - * + * * @return Number of subscribed observers. */ public int getObserverCount() { @@ -108,7 +111,7 @@ public class Observable { /** * Notifies all subscribed observers. - * + * * @param aEvent * Event to send. */ @@ -117,9 +120,11 @@ public class Observable { // potential deadlock // situations. List> myObservers = new ArrayList>(); + synchronized (this) { myObservers.addAll(observers.values()); } + for (Observer observer : myObservers) { notifier.update(observer, observable, aEvent); } @@ -127,14 +132,15 @@ public class Observable { /* * (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!"); + LOGGER.error( + "Still observers registered at finalization of observer!"); + for (Observer observer : observers.values()) { LOGGER.error(" observer: " + observer); } @@ -142,5 +148,4 @@ public class Observable { super.finalize(); } - } diff --git a/support/general/src/main/java/org/wamblee/observer/Observer.java b/support/general/src/main/java/org/wamblee/observer/Observer.java index a0e64314..490c533f 100644 --- a/support/general/src/main/java/org/wamblee/observer/Observer.java +++ b/support/general/src/main/java/org/wamblee/observer/Observer.java @@ -1,32 +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.observer; + /** - * This is a type-safe version of {@link java.util.Observable}. + * This is a type-safe version of {@link java.util.Observable}. * * @author Erik Brakkee */ public interface Observer { - /** * Called when an event has occurred on the observable. - * @param aObservable Observable. - * @param aEvent Event. + * @param aObservable Observable. + * @param aEvent Event. */ - void send(ObservableType aObservable, Event aEvent); + void send(ObservableType aObservable, Event aEvent); } diff --git a/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java b/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java index f09c5f0c..5fe7063f 100644 --- a/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java +++ b/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java @@ -1,35 +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.observer; + /** - * Implementation of notification of subscribers. + * Implementation of notification of subscribers. * * @author Erik Brakkee */ public interface ObserverNotifier { - /** - * Notifies an observer. + * Notifies an observer. * * @param aObserver Observer to notify - * @param aObservable Observable at which the event occured. - * @param aEvent Event that occured. + * @param aObservable Observable at which the event occured. + * @param aEvent Event that occured. */ - void update(Observer aObserver, ObservableType aObservable, Event aEvent); - + void update(Observer aObserver, + ObservableType aObservable, Event aEvent); } diff --git a/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java b/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java index c4b63c3f..3412c0fe 100644 --- a/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java +++ b/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java @@ -1,82 +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.persistence; import java.io.Serializable; + /** - * Default implementation of Persistent. + * Default implementation of Persistent. * * @author Erik Brakkee */ public abstract class AbstractPersistent implements Persistent { - /** - * Primary key. + * Primary key. */ - private Serializable primaryKey; - + private Serializable primaryKey; + /** - * Version. + * Version. */ - private int version; - - /** - * Constructs the object. + private int version; + +/** + * Constructs the object. * */ - protected AbstractPersistent() { - primaryKey = null; - version = -1; + protected AbstractPersistent() { + primaryKey = null; + version = -1; } - - /** - * Copy constructor. - * @param aPersistent Object to copy. + +/** + * Copy constructor. + * @param aPersistent Object to copy. */ protected AbstractPersistent(AbstractPersistent aPersistent) { - primaryKey = aPersistent.primaryKey; - version = aPersistent.version; + primaryKey = aPersistent.primaryKey; + version = aPersistent.version; } /* (non-Javadoc) * @see org.wamblee.persistence.Persistent#getPrimaryKey() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Serializable getPrimaryKey() { - return primaryKey; + return primaryKey; } - + /* (non-Javadoc) * @see org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable) */ + /** + * DOCUMENT ME! + * + * @param aKey DOCUMENT ME! + */ public void setPrimaryKey(Serializable aKey) { - primaryKey = aKey; + primaryKey = aKey; } - + /* (non-Javadoc) * @see org.wamblee.persistence.Persistent#getPersistedVersion() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public int getPersistedVersion() { - return version; + return version; } - + /* (non-Javadoc) * @see org.wamblee.persistence.Persistent#setPersistedVersion(int) */ + /** + * DOCUMENT ME! + * + * @param aVersion DOCUMENT ME! + */ public void setPersistedVersion(int aVersion) { version = aVersion; } diff --git a/support/general/src/main/java/org/wamblee/persistence/Persistent.java b/support/general/src/main/java/org/wamblee/persistence/Persistent.java index 57faf95e..5962d5f3 100644 --- a/support/general/src/main/java/org/wamblee/persistence/Persistent.java +++ b/support/general/src/main/java/org/wamblee/persistence/Persistent.java @@ -1,58 +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.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 + * 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. + * should exclude the primary key and version from determining equality. */ public interface Persistent { - /** - * Gets the primary key. + * Gets the primary key. + * * @return Primary key. - * @see #setPrimaryKey(Serializable) + * + * @see #setPrimaryKey(Serializable) */ - Serializable getPrimaryKey(); - + Serializable getPrimaryKey(); + /** - * Sets the primary key. + * Sets the primary key. + * * @param aKey Primary key. - * @see #getPrimaryKey() + * + * @see #getPrimaryKey() */ - void setPrimaryKey(Serializable aKey); - + void setPrimaryKey(Serializable aKey); + /** - * Gets the version. - * @return Version. + * Gets the version. + * + * @return Version. + * * @see #setPersistedVersion(int) */ - int getPersistedVersion(); - + int getPersistedVersion(); + /** - * Sets the version. - * @param aVersion Version. + * Sets the version. + * + * @param aVersion Version. + * * @see #getPersistedVersion() */ - void setPersistedVersion(int aVersion); + void setPersistedVersion(int aVersion); } diff --git a/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java b/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java index a1fa5522..87a0b8c5 100644 --- a/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java +++ b/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java @@ -1,79 +1,91 @@ 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 getAllMethods(Class aClass) { + Map found = new HashMap(); + getAllMethods(aClass, found); + + return new ArrayList(found.values()); + } + + private static void getAllMethods(Class aClass, Map aFound) { + List 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(); - /** - * 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 getAllMethods(Class aClass) { - - Map found = new HashMap(); - getAllMethods(aClass, found); - return new ArrayList(found.values()); - } - - private static void getAllMethods(Class aClass, Map aFound) { - List 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); - } - } + if (superClass != null) { + getAllMethods(superClass, aFound); + } + } } diff --git a/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java b/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java index ba2d875c..5fe5afb1 100644 --- a/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java +++ b/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java @@ -1,21 +1,23 @@ /* * 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 org.wamblee.io.ClassPathResource; +import org.wamblee.io.InputResource; + import java.io.IOException; import javax.xml.transform.Source; @@ -23,17 +25,14 @@ 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. @@ -41,20 +40,29 @@ public class ClasspathUriResolver implements URIResolver { /* * (non-Javadoc) - * + * * @see javax.xml.transform.URIResolver#resolve(java.lang.String, * java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aHref DOCUMENT ME! + * @param aBase DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws TransformerException DOCUMENT ME! + */ public Source resolve(String aHref, String aBase) - throws TransformerException { + 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); + "Could not get XSLT style sheet in classpath '" + aHref + "'", e); } } - } diff --git a/support/general/src/main/java/org/wamblee/xml/DomUtils.java b/support/general/src/main/java/org/wamblee/xml/DomUtils.java index 3825bacd..36f60773 100644 --- a/support/general/src/main/java/org/wamblee/xml/DomUtils.java +++ b/support/general/src/main/java/org/wamblee/xml/DomUtils.java @@ -1,26 +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.xml; +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; + 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; @@ -34,20 +54,6 @@ 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. @@ -55,12 +61,14 @@ import org.xml.sax.SAXException; * @author Erik Brakkee */ public final class DomUtils { - + /** + * DOCUMENT ME! + */ private static final Log LOG = LogFactory.getLog(DomUtils.class); - /** +/** * Disabled default constructor. - * + * */ private DomUtils() { // Empty. @@ -68,29 +76,35 @@ public final class DomUtils { /** * Parses an XML document from a string. - * - * @param aDocument - * document. + * + * @param aDocument document. + * * @return + * + * @throws XMLException DOCUMENT ME! */ 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. + * + * @param aIs Input stream. + * * @return + * + * @throws XMLException DOCUMENT ME! */ public static Document read(InputStream aIs) throws XMLException { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); + .newDocumentBuilder(); + return builder.parse(aIs); - } catch (SAXException e) { + } catch (SAXException e) { throw new XMLException(e.getMessage(), e); } catch (IOException e) { throw new XMLException(e.getMessage(), e); @@ -107,22 +121,22 @@ public final class DomUtils { /** * Reads and validates a document against a schema. - * - * @param aIs - * Input stream. - * @param aSchema - * Schema. + * + * @param aIs Input stream. + * @param aSchema Schema. + * * @return Parsed and validated document. + * + * @throws XMLException DOCUMENT ME! */ public static Document readAndValidate(InputStream aIs, InputStream aSchema) - throws XMLException { - + throws XMLException { try { - final Schema schema = SchemaFactory.newInstance( - XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( - new StreamSource(aSchema)); + final Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI) + .newSchema(new StreamSource(aSchema)); - final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + final DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); factory.setValidating(true); factory.setNamespaceAware(true); factory.setSchema(schema); @@ -140,59 +154,65 @@ public final class DomUtils { } 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. + * + * @param aDocument Document to serialize. + * @param aOs Output stream. + * + * @throws IOException DOCUMENT ME! */ public static void serialize(Document aDocument, OutputStream aOs) - throws IOException { + throws IOException { XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat()); serializer.serialize(aDocument); } /** * Serializes an XML document. - * - * @param aDocument - * Document to serialize. + * + * @param aDocument Document to serialize. + * * @return Serialized document. + * + * @throws IOException DOCUMENT ME! */ - public static String serialize(Document aDocument) throws IOException { + 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. + * + * @param aDocument Document to convert. + * * @return W3C DOM document. + * + * @throws DocumentException DOCUMENT ME! */ public static Document convert(org.dom4j.Document aDocument) - throws DocumentException { + throws DocumentException { return new DOMWriter().write(aDocument); } /** * Converts a W3C DOM document into a dom4j document. - * - * @param aDocument - * Document to convert. + * + * @param aDocument Document to convert. + * * @return Dom4j document. */ public static org.dom4j.Document convert(Document aDocument) { @@ -202,16 +222,17 @@ public final class DomUtils { /** * 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. + * + * @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); @@ -221,27 +242,31 @@ public final class DomUtils { /** * Removes duplicate attributes from an element. - * - * @param aElement - * Element. + * + * @param aElement Element. */ private static void removeDuplicateAttributes(Element aElement) { - NamedNodeMap attributes = aElement.getAttributes(); + NamedNodeMap attributes = aElement.getAttributes(); Map uniqueAttributes = new TreeMap(); - List attlist = new ArrayList(); + List attlist = new ArrayList(); + 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() + "'"); + + 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/support/general/src/main/java/org/wamblee/xml/XMLException.java b/support/general/src/main/java/org/wamblee/xml/XMLException.java index 06363c42..4b40c571 100644 --- a/support/general/src/main/java/org/wamblee/xml/XMLException.java +++ b/support/general/src/main/java/org/wamblee/xml/XMLException.java @@ -1,33 +1,42 @@ /* * 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. + * Exception thrown in case of XML parsing problems. * * @author Erik Brakkee */ public class XMLException extends Exception { - - public XMLException(String aMsg) { - super(aMsg); +/** + * Creates a new XMLException object. + * + * @param aMsg DOCUMENT ME! + */ + public XMLException(String aMsg) { + super(aMsg); } - - public XMLException(String aMsg, Throwable aCause) { + +/** + * Creates a new XMLException object. + * + * @param aMsg DOCUMENT ME! + * @param aCause DOCUMENT ME! + */ + public XMLException(String aMsg, Throwable aCause) { super(aMsg, aCause); } } diff --git a/support/general/src/main/java/org/wamblee/xml/XslTransformer.java b/support/general/src/main/java/org/wamblee/xml/XslTransformer.java index 0e9ffee4..640aece3 100644 --- a/support/general/src/main/java/org/wamblee/xml/XslTransformer.java +++ b/support/general/src/main/java/org/wamblee/xml/XslTransformer.java @@ -1,21 +1,24 @@ /* * 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 org.w3c.dom.Document; + +import org.wamblee.io.FileResource; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -33,8 +36,6 @@ 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. @@ -42,12 +43,14 @@ import org.wamblee.io.FileResource; * @author Erik Brakkee */ public class XslTransformer { - + /** + * DOCUMENT ME! + */ private TransformerFactory factory; - /** +/** * Constructs the URL resolver. - * + * * @param aResolver * URI resolver to use. */ @@ -56,121 +59,124 @@ public class XslTransformer { factory.setURIResolver(aResolver); } - /** +/** * Constructs the XSLT processor. - * + * */ public XslTransformer() { factory = TransformerFactory.newInstance(); } /** - * Resolves an XSLT based on URI. - * @param aXslt XSLT to resolve, + * 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. + * + * @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()); + .getInputStream()); } catch (IOException e) { throw new TransformerException(e.getMessage(), e); } } else { - throw new TransformerException("Cannot read '" + aXslt + "'"); + 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. + * 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. + * + * @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); + 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. + * + * @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. + * + * @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)); + 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. + * + * @param aDocument Document to transform. + * @param aXslt XSL transformation. + * * @return Transformed document. + * + * @throws IOException DOCUMENT ME! + * @throws TransformerException DOCUMENT ME! */ 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); + 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. + * + * @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 { + 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); + throw new TransformerException("Configuration problem of XSLT transformation", + e); } } } diff --git a/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java b/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java index 70d1b7af..4ed1d2d2 100644 --- a/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java +++ b/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java @@ -1,175 +1,182 @@ /* * 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; +import java.io.IOException; + + /** - * Cached object test. + * 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 computation; + private int ncomputations; - private static final int OBJECT_KEY = 10; - - private CachedObject.Computation computation; - private int ncomputations; - /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); - computation = new CachedObject.Computation() { - public Integer getObject(Integer aObjectKey) { - ncomputations++; - return compute(aObjectKey); - }; - }; - ncomputations = 0; + computation = new CachedObject.Computation() { + public Integer getObject(Integer aObjectKey) { + ncomputations++; + + return compute(aObjectKey); + } + ; + }; + ncomputations = 0; } - - private int compute(int aValue) { + + private int compute(int aValue) { return aValue + 10; } - - private CachedObject createCached(Cache aCache) { - return new CachedObject(aCache, OBJECT_KEY, computation); + + private CachedObject createCached( + Cache aCache) { + return new CachedObject(aCache, OBJECT_KEY, + computation); } /** - * Verifies that upon first use, the cached object uses the computation to - * retrieve the object. + * Verifies that upon first use, the cached object uses the computation to + * retrieve the object. * */ - public void testComputation() { - CachedObject cached = createCached(new ZeroCache()); + public void testComputation() { + CachedObject cached = createCached(new ZeroCache()); int value = cached.get(); assertEquals(compute(OBJECT_KEY), value); - assertEquals(1, ncomputations); + assertEquals(1, ncomputations); } - - public void testInvalidateCache() { - CachedObject cached = createCached(new ForeverCache()); + + public void testInvalidateCache() { + CachedObject cached = createCached(new ForeverCache()); int value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(1, ncomputations); - cached.invalidate(); + cached.invalidate(); value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(2, ncomputations); } - + public void testBehaviorEhCache() throws CacheException, IOException { - Cache cache = new EhCache(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "test"); + Cache cache = new EhCache(new TestResource( + CachedObjectTest.class, EHCACHE_CONFIG), "test"); CachedObject cached = createCached(cache); - - assertTrue( cache == cached.getCache()); + + 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(); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(1, ncomputations); - + // Cache expiry. - TimingUtils.sleep(6000); - value = cached.get(); + TimingUtils.sleep(6000); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(2, ncomputations); - + // Should still be cached now. - value = cached.get(); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(2, ncomputations); - + // explicit invalidation. - cached.invalidate(); - value = cached.get(); + cached.invalidate(); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(3, ncomputations); - } - + public void testBehaviorEhCacheDefault() throws CacheException, IOException { - Cache cache = new EhCache(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "undefined"); + Cache cache = new EhCache(new TestResource( + CachedObjectTest.class, EHCACHE_CONFIG), "undefined"); CachedObject cached = createCached(cache); - - assertTrue( cache == cached.getCache()); + + 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(); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(1, ncomputations); - + // Cache expiry. - TimingUtils.sleep(6000); - value = cached.get(); + TimingUtils.sleep(6000); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(2, ncomputations); - + // Should still be cached now. - value = cached.get(); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(2, ncomputations); - } - - - public void testBehaviorForeverCache() { - CachedObject cached = createCached(new ForeverCache()); + + public void testBehaviorForeverCache() { + CachedObject cached = createCached(new ForeverCache()); int value = cached.get(); assertEquals(compute(OBJECT_KEY), value); - assertEquals(1, ncomputations); - for (int ncomp = 2; ncomp <= 100; ncomp++) { - value = cached.get(); + 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 cached = createCached(new ZeroCache()); + + public void testBehaviorZeroCache() { + CachedObject cached = createCached(new ZeroCache()); int value = cached.get(); assertEquals(compute(OBJECT_KEY), value); - assertEquals(1, ncomputations); - for (int ncomp = 2; ncomp <= 100; ncomp++) { - value = cached.get(); + 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(); + + cached.invalidate(); + value = cached.get(); assertEquals(compute(OBJECT_KEY), value); assertEquals(101, ncomputations); } diff --git a/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java b/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java index 1e56eac1..6e6259fa 100644 --- a/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java +++ b/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java @@ -1,42 +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 junit.framework.TestCase; import org.wamblee.conditions.Condition; + import org.wamblee.test.AssertionUtils; -import junit.framework.TestCase; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; -public class CollectionFilterTest extends TestCase { - - public void testFilter() { - List list = Arrays.asList(new String[] { "x", "y", "z", "y" }); - List result = new ArrayList(); - CollectionFilter.filter(list, result, - new Condition() { - @Override - public boolean matches(String aObject) { - return aObject.equals("y"); - } - }); - AssertionUtils.assertEquals(new String[] { "y", "y" }, result.toArray()); - } +public class CollectionFilterTest extends TestCase { + public void testFilter() { + List list = Arrays.asList(new String[] { "x", "y", "z", "y" }); + List result = new ArrayList(); + CollectionFilter.filter(list, result, + new Condition() { + @Override + public boolean matches(String aObject) { + return aObject.equals("y"); + } + }); + AssertionUtils.assertEquals(new String[] { "y", "y" }, result.toArray()); + } } diff --git a/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java b/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java index 6c9df461..0ac0ba1b 100644 --- a/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java +++ b/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java @@ -1,25 +1,25 @@ /* * 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.TestCase; + import org.wamblee.test.EventTracker; import org.wamblee.test.TimingUtils; -import junit.framework.TestCase; /** * Tests for the JVMLock. @@ -27,37 +27,32 @@ import junit.framework.TestCase; * @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 tracker; /* * (non-Javadoc) - * + * * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { tracker = new EventTracker(); } - - protected EventTracker getTracker() { + + protected EventTracker getTracker() { return tracker; } /** - * Must be implemented to generate the events - * {@link #STARTED}, {@link #ACQUIRED}, and {@link #RELEASED} in + * 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. + * @return Thread which does the work. */ protected abstract Thread runThread(); @@ -68,24 +63,30 @@ public abstract class AbstractLockTestCase extends TestCase { Thread t1 = runThread(); Thread t2 = runThread(); TimingUtils.sleep(SLEEP_TIME / 10); // give threads a chance to start - // up. + // up. + assertEquals(2, tracker.getEventCount(STARTED)); // both threads - // should have - // started. + // should have + // started. + assertEquals(1, tracker.getEventCount(ACQUIRED)); // one thread has - // acquired the - // lock. + // acquired the + // lock. + TimingUtils.sleep(SLEEP_TIME); assertEquals(2, tracker.getEventCount(ACQUIRED)); // now the other - // thread could also - // acquire the lock + // thread could also + // acquire the lock + assertEquals(1, tracker.getEventCount(RELEASED)); // and the first - // thread has - // released it. + // thread has + // released it. + TimingUtils.sleep(SLEEP_TIME); assertEquals(2, tracker.getEventCount(RELEASED)); // both threads - // should be - // finished. + // should be + // finished. + t1.join(); t2.join(); } diff --git a/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java b/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java index 8475f198..6f02b1c0 100644 --- a/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java +++ b/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java @@ -1,35 +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.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 @@ -40,16 +39,18 @@ public class JvmLockTest extends AbstractLockTestCase { 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); - }; - }); + 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/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java b/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java index e0d22f77..2e799624 100644 --- a/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java +++ b/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java @@ -1,18 +1,18 @@ /* * 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; @@ -27,20 +27,22 @@ import junit.framework.TestCase; */ 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; + private int nReaders; + private int nWriters; /** * Constructor for ReadWriteLockTest. @@ -115,7 +117,7 @@ public class ReadWriteLockTest extends TestCase { public void testMultipleReaders() throws InterruptedException { Runnable runnable = new ReadLocker(lock, this, TWO_SECONDS); - Thread t1 = new Thread(runnable); + Thread t1 = new Thread(runnable); t1.start(); Thread t2 = new Thread(runnable); @@ -133,8 +135,8 @@ public class ReadWriteLockTest extends TestCase { */ public void testSingleWriter() throws InterruptedException { WriteLocker writer = new WriteLocker(lock, this, ONE_SECOND); - Thread t1 = new Thread(writer); - Thread t2 = new Thread(writer); + Thread t1 = new Thread(writer); + Thread t2 = new Thread(writer); t1.start(); t2.start(); @@ -151,10 +153,11 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testMultipleWriters() throws InterruptedException { - WriteLocker writer1 = new WriteLocker(lock, this, HALF_SECOND + ONE_SECOND); + 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); + Thread t1 = new Thread(writer1); + Thread t2 = new Thread(writer2); t1.start(); Thread.sleep(HALF_SECOND); @@ -180,10 +183,10 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testReadWrite1() throws InterruptedException { - ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS); - Thread t1 = new Thread(readLocker); + 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); + Thread t2 = new Thread(writeLocker); t1.start(); // acquire read lock Thread.sleep(HALF_SECOND); @@ -213,12 +216,14 @@ public class ReadWriteLockTest extends TestCase { * @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); + 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); + Thread t3 = new Thread(writeLocker); t1.start(); // acquire read lock [0, 2.5] Thread.sleep(ONE_SECOND); @@ -259,10 +264,10 @@ public class ReadWriteLockTest extends TestCase { * @throws InterruptedException May not occur. */ public void testReadWrite3() throws InterruptedException { - ReadLocker readLocker = new ReadLocker(lock, this, TWO_SECONDS); - Thread t1 = new Thread(readLocker); + 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); + Thread t2 = new Thread(writeLocker); t2.start(); // acquire write lock Thread.sleep(HALF_SECOND); @@ -447,15 +452,15 @@ public class ReadWriteLockTest extends TestCase { * lock, and performs a callback after the lock has been released. */ class ReadLocker implements Runnable { - private ReadWriteLock lock; + private ReadWriteLock lock; private ReadWriteLockTest lockTest; - private int sleepTime; + private int sleepTime; public ReadLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest, int aSleepTime) { - lock = aLock; - lockTest = aLockTest; - sleepTime = aSleepTime; + lock = aLock; + lockTest = aLockTest; + sleepTime = aSleepTime; } public void run() { @@ -465,8 +470,8 @@ class ReadLocker implements Runnable { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { - Assert.fail("ReadLocker thread was interrupted." - + Thread.currentThread()); + Assert.fail("ReadLocker thread was interrupted." + + Thread.currentThread()); } lock.releaseRead(); @@ -481,15 +486,15 @@ class ReadLocker implements Runnable { * lock, and performs a callback after the lock has been released. */ class WriteLocker implements Runnable { - private ReadWriteLock lock; + private ReadWriteLock lock; private ReadWriteLockTest lockTest; - private int sleepTime; + private int sleepTime; public WriteLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest, int aSleepTime) { - lock = aLock; - lockTest = aLockTest; - sleepTime = aSleepTime; + lock = aLock; + lockTest = aLockTest; + sleepTime = aSleepTime; } public void run() { @@ -499,8 +504,8 @@ class WriteLocker implements Runnable { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { - Assert.fail("WriteLocker thread was interrupted: " - + Thread.currentThread()); + Assert.fail("WriteLocker thread was interrupted: " + + Thread.currentThread()); } lock.releaseWrite(); diff --git a/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java b/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java index 81c4e4ed..74682373 100644 --- a/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java +++ b/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java @@ -1,64 +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.conditions; +import junit.framework.TestCase; + import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; /** - * Tests the Or Condition. + * Tests the Or Condition. * * @author Erik Brakkee */ public class AndConditionTest extends TestCase { - - public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { - AndCondition and = new AndCondition(new FixedCondition(aFirst), - new FixedCondition(aSecond)); + public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { + AndCondition and = new AndCondition(new FixedCondition( + aFirst), new FixedCondition(aSecond)); assertEquals(aResult, and.matches(0)); } - - public void checkResult(boolean[] aValues, boolean aResult) { + + public void checkResult(boolean[] aValues, boolean aResult) { List> conditions = new ArrayList>(); - for (boolean value: aValues) { - conditions.add(new FixedCondition(value)); + + for (boolean value : aValues) { + conditions.add(new FixedCondition(value)); } + AndCondition and = new AndCondition(conditions); assertEquals(aResult, and.matches(new Integer(0))); } /** - * Checks all combinations of two conditions. + * Checks all combinations of two conditions. * */ - public void testTwoConditions() { + public void testTwoConditions() { checkResult(false, false, false); checkResult(true, false, false); - checkResult(false, true, 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); + + 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/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java b/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java index decdb53b..ccd2d734 100644 --- a/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java +++ b/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java @@ -1,39 +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.conditions; + /** - * Test condition object. + * Test condition object. * * @author Erik Brakkee */ public class GreaterThanCondition implements Condition { - - private int value; - - public GreaterThanCondition(int aValue) { - value = aValue; + 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; + return aObject > value; } - } diff --git a/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java b/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java index 4f8e419c..f7d45a47 100644 --- a/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java +++ b/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java @@ -1,39 +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.conditions; + /** - * Test condition object. + * Test condition object. * * @author Erik Brakkee */ public class LessThanCondition implements Condition { - - private int value; - - public LessThanCondition(int aValue) { - value = aValue; + 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; + return aObject < value; } - } diff --git a/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java b/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java index c3f7df1e..a757520b 100644 --- a/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java +++ b/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java @@ -1,64 +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.conditions; +import junit.framework.TestCase; + import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; /** - * Tests the Or Condition. + * Tests the Or Condition. * * @author Erik Brakkee */ public class OrConditionTest extends TestCase { - - public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { - OrCondition or = new OrCondition(new FixedCondition(aFirst), - new FixedCondition(aSecond)); + public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { + OrCondition or = new OrCondition(new FixedCondition( + aFirst), new FixedCondition(aSecond)); assertEquals(aResult, or.matches(0)); } - - public void checkResult(boolean[] aValues, boolean aResult) { + + public void checkResult(boolean[] aValues, boolean aResult) { List> conditions = new ArrayList>(); - for (boolean value: aValues) { - conditions.add(new FixedCondition(value)); + + for (boolean value : aValues) { + conditions.add(new FixedCondition(value)); } + OrCondition or = new OrCondition(conditions); assertEquals(aResult, or.matches(new Integer(0))); } /** - * Checks all combinations of two conditions. + * Checks all combinations of two conditions. * */ - public void testTwoConditions() { + public void testTwoConditions() { checkResult(false, false, false); checkResult(true, false, true); - checkResult(false, true, 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); + + 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/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java b/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java index 9f494fb6..33df8e97 100644 --- a/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java +++ b/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java @@ -1,79 +1,86 @@ /* * 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}. + * 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 condition = new PropertyRegexCondition(aProperty, aRegex, aToLower ); + private boolean match(String aProperty, String aRegex, boolean aToLower, + TestBean aBean) { + PropertyRegexCondition condition = new PropertyRegexCondition(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)); + + 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. + * Verifies correct matching behavior for several cases. * */ public void testMatchProperty() { - TestBean bean = new TestBean("Hallo"); - checkMatch("value", "Hallo", false, bean, true); + 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. + * Uses property regex condition for non-existing property. + * Verifies that a runtime exception is thrown. * */ - public void testWrongProperty() { + public void testWrongProperty() { TestBean bean = new TestBean("Hallo"); - try { - match("bla", ".*", false, bean); - } catch (RuntimeException e) { - return; // ok + + try { + match("bla", ".*", false, bean); + } catch (RuntimeException e) { + return; // ok } + fail(); } - + /** - * Applies condition to a private property. Verifies that a runtime - * exception is thrown. + * Applies condition to a private property. Verifies that a runtime + * exception is thrown. * */ - public void testPrivateProperty() { + public void testPrivateProperty() { TestBean bean = new TestBean("Hallo"); - try { - match("privateValue", ".*", false, bean); - } catch (RuntimeException e) { - return; // ok + + try { + match("privateValue", ".*", false, bean); + } catch (RuntimeException e) { + return; // ok } + fail(); } } diff --git a/support/general/src/test/java/org/wamblee/conditions/TestBean.java b/support/general/src/test/java/org/wamblee/conditions/TestBean.java index 24c26dea..83f0cf42 100644 --- a/support/general/src/test/java/org/wamblee/conditions/TestBean.java +++ b/support/general/src/test/java/org/wamblee/conditions/TestBean.java @@ -1,39 +1,38 @@ /* * 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; - private String value; - - public TestBean(String aValue) { - value = aValue; + public TestBean(String aValue) { + value = aValue; } - - public String getValue() { - return value; + + public String getValue() { + return value; } - - private String getPrivateValue() { - return value; + + private String getPrivateValue() { + return value; } } diff --git a/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java b/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java index 2c9f898f..61c4533f 100644 --- a/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java +++ b/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java @@ -1,23 +1,23 @@ /* * 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 @@ -26,63 +26,63 @@ import junit.framework.TestCase; * @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"); + 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. - * + * 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"); + 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. - * + * bean factory defined in it. + * Verifies that BeanFactoryException is thrown. + * */ public void testNonExistentBeanFactory() { try { - BeanKernel - .lookupBeanFactory("org/wamblee/general/beankernel-wrong.properties"); + 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 + // default + // property + // lookup + BeanFactory factory = BeanKernel.getBeanFactory(); assertNotNull(factory); assertEquals("hello", factory.find(String.class)); } - } diff --git a/support/general/src/test/java/org/wamblee/general/PairTest.java b/support/general/src/test/java/org/wamblee/general/PairTest.java index dcb6f614..99b73cc5 100644 --- a/support/general/src/test/java/org/wamblee/general/PairTest.java +++ b/support/general/src/test/java/org/wamblee/general/PairTest.java @@ -1,37 +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.general; import junit.framework.TestCase; + /** - * Tests the pair class. + * Tests the pair class. */ public class PairTest extends TestCase { - - public void testPair() { - Pair pair = new Pair(10, "hello"); + public void testPair() { + Pair pair = new Pair(10, "hello"); assertEquals(new Integer(10), pair.getFirst()); assertEquals("hello", pair.getSecond()); - + Pair pair2 = new Pair(pair); assertEquals(new Integer(10), pair2.getFirst()); assertEquals("hello", pair2.getSecond()); - - } } diff --git a/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java b/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java index 6198e9ba..3888e047 100644 --- a/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java +++ b/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java @@ -1,38 +1,37 @@ /* * 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 Object find(String aId) { - return null; - } + @Override + public T find(Class aClass) { + if (aClass.equals(String.class)) { + return (T) "hello"; + } - @Override - public T find(Class aClass) { - if ( aClass.equals(String.class)) { - return (T)"hello"; - } - return null; - } - - @Override - public T find(String aId, Class aClass) { - return null; - } + return null; + } + @Override + public T find(String aId, Class aClass) { + return null; + } } diff --git a/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java b/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java index 70b05ab5..92e55db5 100644 --- a/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java +++ b/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java @@ -1,35 +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.io; +import junit.framework.TestCase; + 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( @@ -42,7 +40,7 @@ public class ClassPathResourceTest extends TestCase { /** * Loads a non-existing resource from the class path. Verifies that an IO * exception is thrown. - * + * */ public void testResourceNotFound() { try { @@ -52,6 +50,7 @@ public class ClassPathResourceTest extends TestCase { } catch (IOException e) { return; // ok } + fail(); } } diff --git a/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java b/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java index e0048c08..ac5fbf70 100644 --- a/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java +++ b/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,108 +15,103 @@ */ package org.wamblee.io; -import static org.mockito.Mockito.*; import junit.framework.TestCase; import org.apache.oro.io.AwkFilenameFilter; - +import static org.mockito.Mockito.*; 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. - - - } + 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/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java b/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java index 4f301cf7..278b18d4 100644 --- a/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java +++ b/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java @@ -1,51 +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 org.apache.oro.io.AwkFilenameFilter; + 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 (;;) { + 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/support/general/src/test/java/org/wamblee/io/FileResourceTest.java b/support/general/src/test/java/org/wamblee/io/FileResourceTest.java index c1564f04..a69a1b44 100644 --- a/support/general/src/test/java/org/wamblee/io/FileResourceTest.java +++ b/support/general/src/test/java/org/wamblee/io/FileResourceTest.java @@ -1,43 +1,41 @@ /* * 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 junit.framework.TestCase; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import junit.framework.TestCase; - /** - * Tests the file resource. + * 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")); + 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); @@ -46,17 +44,18 @@ public class FileResourceTest extends TestCase { /** * 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")); + 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/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java b/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java index ad3b4e20..fd507caf 100644 --- a/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java +++ b/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,6 +15,12 @@ */ package org.wamblee.io; +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -22,348 +28,363 @@ 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()); - } - } - } + 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/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java b/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java index 1cf9478f..7ec09ac7 100644 --- a/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java +++ b/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java @@ -1,50 +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 junit.framework.TestCase; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import junit.framework.TestCase; - /** - * Tests the stream resource. + * 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()); + 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/support/general/src/test/java/org/wamblee/io/TestData.java b/support/general/src/test/java/org/wamblee/io/TestData.java index 1418f6b1..1ddf3ada 100644 --- a/support/general/src/test/java/org/wamblee/io/TestData.java +++ b/support/general/src/test/java/org/wamblee/io/TestData.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,6 +15,8 @@ */ package org.wamblee.io; +import junit.framework.Assert; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -22,170 +24,168 @@ 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); - } + 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/support/general/src/test/java/org/wamblee/io/TestResource.java b/support/general/src/test/java/org/wamblee/io/TestResource.java index ec28290f..4f0f09df 100644 --- a/support/general/src/test/java/org/wamblee/io/TestResource.java +++ b/support/general/src/test/java/org/wamblee/io/TestResource.java @@ -1,19 +1,18 @@ /* * 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; @@ -23,25 +22,24 @@ 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. + * 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)); + 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. + * 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) { + private static File getFile(Class aClass, String aName) { File dir = FileSystemUtils.getTestInputDir(aClass); + return new File(dir, aName); } - } diff --git a/support/general/src/test/java/org/wamblee/observer/ObservableTest.java b/support/general/src/test/java/org/wamblee/observer/ObservableTest.java index e26571a4..5a9d2ecb 100644 --- a/support/general/src/test/java/org/wamblee/observer/ObservableTest.java +++ b/support/general/src/test/java/org/wamblee/observer/ObservableTest.java @@ -1,143 +1,145 @@ /* * 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 junit.framework.TestCase; + +import org.mockito.InOrder; +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 observable; + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + observed = new Integer(1); + observable = new Observable(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 subscriptions = new ArrayList(); + + 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 observer = mock(Observer.class); + + long subscription = observable.subscribe(observer); + + assertEquals(1, observable.getObserverCount()); + + try { + observable.unsubscribe(subscription + 1); + } catch (IllegalArgumentException e) { + return; // ok + } - private static final int SUBSCRIBER_COUNT = 100; - - private static final String UPDATE = "send"; - - private Integer observed; - private Observable observable; - - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - super.setUp(); - observed = new Integer(1); - observable = new Observable(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 subscriptions = new ArrayList(); - 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 observer = mock(Observer.class); - - long subscription = observable.subscribe(observer); - - assertEquals(1, observable.getObserverCount()); - - try { - observable.unsubscribe(subscription + 1); - } catch (IllegalArgumentException e) { - return; // ok - } - fail(); - } + fail(); + } } diff --git a/support/general/src/test/java/org/wamblee/test/AssertionUtils.java b/support/general/src/test/java/org/wamblee/test/AssertionUtils.java index a0216a8b..966a52e4 100644 --- a/support/general/src/test/java/org/wamblee/test/AssertionUtils.java +++ b/support/general/src/test/java/org/wamblee/test/AssertionUtils.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,15 +15,16 @@ */ package org.wamblee.test; +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + 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. @@ -31,20 +32,19 @@ import org.apache.commons.logging.LogFactory; * @author Erik Brakkee */ public final class AssertionUtils { - - private static final Log LOG = LogFactory.getLog(AssertionUtils.class); + 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 @@ -53,11 +53,10 @@ public final class AssertionUtils { public static void assertEquals(T[] aExpected, T[] aActual) { assertEquals("", aExpected, aActual); } - /** * Asserts that two object arrays are equal. - * + * * @param aMsg * Message. * @param aExpected @@ -65,24 +64,21 @@ public final class AssertionUtils { * @param aActual * Actual array. */ - public static 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); + public static 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]); + 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 @@ -90,11 +86,10 @@ public final class AssertionUtils { * @param aActual * Actual result. */ - public static void assertEquals(String aMsg, T aExpected, - T aActual) { + public static void assertEquals(String aMsg, T aExpected, T aActual) { if (aExpected instanceof Object[]) { AssertionUtils.assertEquals(aMsg, (Object[]) aExpected, - (Object[]) aActual); + (Object[]) aActual); return; } @@ -105,7 +100,7 @@ public final class AssertionUtils { /** * 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 @@ -113,44 +108,44 @@ public final class AssertionUtils { * @param aActual * Actual result. */ - public static void assertEquals(String aMsg, - Map aExpectedMap, Map aActual) { - TestCase.assertEquals("Map sizes differ", aExpectedMap.size(), aActual - .size()); + public static void assertEquals(String aMsg, + Map aExpectedMap, Map 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)); + aActual.containsKey(key)); AssertionUtils.assertEquals("Value of key " + key + " of map", - aExpectedMap.get(key), aActual.get(key)); + 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. + * @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); - } - } + 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); + } + } + } + + public static interface ErroneousCode { + void run() throws Exception; } } diff --git a/support/general/src/test/java/org/wamblee/test/EventTracker.java b/support/general/src/test/java/org/wamblee/test/EventTracker.java index 9e9c472d..94d2f19f 100644 --- a/support/general/src/test/java/org/wamblee/test/EventTracker.java +++ b/support/general/src/test/java/org/wamblee/test/EventTracker.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,24 +15,25 @@ */ package org.wamblee.test; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + 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 * Type of event sent from test code. Usually String will be * sufficient. The event type must provide a sensible implementation @@ -41,7 +42,6 @@ import org.apache.commons.logging.LogFactory; * @author Erik Brakkee */ public class EventTracker { - private static final Log LOG = LogFactory.getLog(EventTracker.class); /** @@ -51,36 +51,39 @@ public class EventTracker { /** * Constructs the event tracker. - * + * */ public EventTracker() { clear(); } - public void clear() { - events = new HashMap>(); - } + public void clear() { + events = new HashMap>(); + } /** * 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 eventList = events.get(current); + if (eventList == null) { eventList = new ArrayList(); events.put(current, eventList); } + eventList.add(aEvent); } /** * Checks if a specific event has happened in a specific thread. - * + * * @param aThread * Thread to check. * @param aEvent @@ -89,15 +92,17 @@ public class EventTracker { */ public synchronized boolean isEventSent(Thread aThread, Event aEvent) { List eventList = events.get(aThread); + if (eventList == null) { return false; } + return eventList.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 @@ -105,42 +110,49 @@ public class EventTracker { */ public synchronized List getEvents(Thread aThread) { List eventList = events.get(aThread); + if (eventList == null) { eventList = Collections.emptyList(); } + return Collections.unmodifiableList(eventList); } /** * Gets the number of times an event was sent summed up - * over all threads. - * + * 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 eventList = events.get(thread); + for (Event event : eventList) { if (event.equals(aEvent)) { count++; } } } + return count; } - + /** - * Gets the total event count over all threads. + * 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; + public synchronized int getEventCount() { + int count = 0; + + for (Thread thread : events.keySet()) { + count += events.get(thread).size(); + } + + return count; } } diff --git a/support/general/src/test/java/org/wamblee/test/TimingUtils.java b/support/general/src/test/java/org/wamblee/test/TimingUtils.java index 82d3c0e8..03bdbc19 100644 --- a/support/general/src/test/java/org/wamblee/test/TimingUtils.java +++ b/support/general/src/test/java/org/wamblee/test/TimingUtils.java @@ -1,30 +1,29 @@ /* * 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. * @@ -32,17 +31,16 @@ public final class TimingUtils { private TimingUtils() { // Empty } - + /** - * Sleeps for a time. - * @param aMillis Number of milliseconds to sleep. + * Sleeps for a time. + * @param aMillis Number of milliseconds to sleep. */ - public static void sleep(int aMillis) { - try { + public static void sleep(int aMillis) { + try { Thread.sleep(aMillis); - } catch (InterruptedException e) { + } catch (InterruptedException e) { TestCase.fail("Who interrupted my sleep?"); } } - } diff --git a/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java b/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java index bd8dddd4..01c90479 100644 --- a/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java +++ b/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java @@ -1,21 +1,25 @@ /* * 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 junit.framework.TestCase; + +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.FileSystemUtils; + import java.io.IOException; import javax.xml.transform.Source; @@ -23,11 +27,6 @@ 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}. @@ -35,42 +34,46 @@ import org.wamblee.io.FileSystemUtils; * @author Erik Brakkee */ public class ClasspathUriResolverTest extends TestCase { - - private URIResolver resolver; - + private URIResolver resolver; + /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { - resolver = new ClasspathUriResolver(); + resolver = new ClasspathUriResolver(); } /** - * Resolves an existing file. Verifies the file is resolved correctly. - * @throws TransformerException + * Resolves an existing file. Verifies the file is resolved correctly. + * @throws TransformerException * @throws IOException */ - public void testResolveExistingFile() throws TransformerException, 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 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. + * 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) { + try { + Source source = resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl", + ""); + } catch (TransformerException e) { return; // ok } + fail(); } } diff --git a/support/general/src/test/java/org/wamblee/xml/XmlUtils.java b/support/general/src/test/java/org/wamblee/xml/XmlUtils.java index fc894251..f35b50cf 100644 --- a/support/general/src/test/java/org/wamblee/xml/XmlUtils.java +++ b/support/general/src/test/java/org/wamblee/xml/XmlUtils.java @@ -1,32 +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.xml; +import junit.framework.TestCase; + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.Element; + 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. @@ -34,10 +34,9 @@ import org.dom4j.Element; * @author Erik Brakkee */ public final class XmlUtils { - /** * Disabled constructor. - * + * */ private XmlUtils() { // Empty @@ -46,60 +45,62 @@ public final class XmlUtils { /** * 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. - * + * 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)); + 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. - * + * 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()); + 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. - * + * 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) { - + Element aActual) { // Name. - TestCase.assertEquals(aMsg + "/name()", aExpected.getName(), aActual - .getName()); + TestCase.assertEquals(aMsg + "/name()", aExpected.getName(), + aActual.getName()); // Text TestCase.assertEquals(aMsg + "/text()", aExpected.getTextTrim(), - aActual.getTextTrim()); + aActual.getTextTrim()); // Attributes List expectedAttrs = aExpected.attributes(); Collections.sort(expectedAttrs, new AttributeComparator()); + List actualAttrs = aActual.attributes(); Collections.sort(actualAttrs, new AttributeComparator()); TestCase.assertEquals("count(" + aMsg + "/@*)", expectedAttrs.size(), - actualAttrs.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)); @@ -109,21 +110,26 @@ public final class XmlUtils { List expectedElems = aExpected.elements(); List actualElems = aActual.elements(); TestCase.assertEquals("count(" + aMsg + "/*)", expectedElems.size(), - actualElems.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 elementIndex = new TreeMap(); + 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 + "]"; + + String msg = aMsg + "/" + expectedElems.get(i).getName() + "[" + + index + "]"; assertEquals(msg, expectedElems.get(i), actualElems.get(i)); } @@ -131,28 +137,27 @@ public final class XmlUtils { /** * Checks equality of two attributes. In case of problems, it - * provides an xpath-like expression describing where the problem is. - * + * 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()); + 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 { + private static final class AttributeComparator implements Comparator { /* * (non-Javadoc) - * + * * @see java.util.Comparator#compare(T, T) */ public int compare(Attribute aAttribute1, Attribute aAttribute2) { diff --git a/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java b/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java index d30e60a6..c43214cd 100644 --- a/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java +++ b/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java @@ -1,21 +1,28 @@ /* * 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 junit.framework.TestCase; + +import org.w3c.dom.Document; + +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.FileSystemUtils; +import org.wamblee.io.InputResource; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -28,12 +35,6 @@ 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. @@ -41,217 +42,218 @@ import org.w3c.dom.Document; * @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_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; + 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)); - + InputResource xmlResource = new ClassPathResource(getResourcePath( + REPORT_XML)); + Source xslt = new StreamSource(new ClassPathResource(getResourcePath( - REPORT_TO_HTML_XSLT)).getInputStream()); + REPORT_TO_HTML_XSLT)).getInputStream()); - byte[] documentData = FileSystemUtils - .read(xmlResource.getInputStream()).getBytes(); + byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream()) + .getBytes(); DocumentBuilder builder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); + .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()); + "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()); + 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()); + REPORT_TO_HTML_XSLT)).getInputStream()); transformer.transform(documentSource, output, xslt); - XmlUtils.assertEquals("document source transform", expected, DomUtils - .read(os.toString())); + XmlUtils.assertEquals("document source transform", expected, + DomUtils.read(os.toString())); xslt = new StreamSource(new ClassPathResource(getResourcePath( - REPORT_TO_HTML_XSLT)).getInputStream()); + REPORT_TO_HTML_XSLT)).getInputStream()); + String result = transformer.textTransform(documentData, xslt); - XmlUtils - .assertEquals("text transform", expected, DomUtils.read(result)); + 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 { + 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()); + 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(); - 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()); + 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(); - 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()); + 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(); - 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()); + REPORT_XML)); + Source xslt = new StreamSource(new ClassPathResource(getResourcePath( + REPORT_TO_HTML2_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils.read(xmlResource.getInputStream()) + .getBytes(); - 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()); + 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()); + 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(); - 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. + * Tests resolving a file using {@link XslTransformer#resolve(String)} with the + * default resolver where the file does not exist. * */ - public void testResolveWithDefaultResolverFileNotFound() { + public void testResolveWithDefaultResolverFileNotFound() { XslTransformer transformer = new XslTransformer(); - try { - Source source = transformer.resolve("org/wamblee/xml/utilities-nonexistent.xsl"); - } catch (TransformerException e) { + + 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. + * Tests resolving a file using {@link XslTransformer#resolve(String)} with the + * default resolver. * */ - public void testResolveWithClasspathResolver() throws Exception { + 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; + 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()); + String expected = FileSystemUtils.read(new ClassPathResource( + getResourcePath(INCLUDED_XSL_FILE)).getInputStream()); assertEquals(expected, data); } - } - - diff --git a/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java b/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java index a20a9f65..0c22b230 100644 --- a/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java +++ b/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java @@ -1,55 +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.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. + * Locking advice. This automatically synchronized an object using a given + * lock. * * @author Erik Brakkee */ public class LockAdvice implements MethodInterceptor { - /** - * Lock to use. + * Lock to use. */ - private Lock lock; - - /** + private Lock lock; + +/** * Constructs lock advice. * @param aLock Lock to use. */ - public LockAdvice(Lock aLock) { - lock = aLock; + 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 { + /** + * DOCUMENT ME! + * + * @param aInvocation DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws Throwable DOCUMENT ME! + */ + public Object invoke(MethodInvocation aInvocation) + throws Throwable { lock.acquire(); - try { - return aInvocation.proceed(); - } finally { + + try { + return aInvocation.proceed(); + } finally { lock.release(); } } - } diff --git a/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java b/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java index 56efedc3..92de9644 100644 --- a/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java +++ b/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,11 +18,14 @@ 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 @@ -30,10 +33,12 @@ import org.wamblee.general.BeanKernel; * it must tbe subclassed to provide a default constructor. */ public class SpringBeanFactory implements BeanFactory { - + /** + * DOCUMENT ME! + */ private BeanFactoryReference factoryReference; - /** +/** * Constructs the bean factory. * * @param aSelector @@ -44,55 +49,82 @@ public class SpringBeanFactory implements BeanFactory { public SpringBeanFactory(String aSelector, String aFactoryName) { try { BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator - .getInstance(aSelector); + .getInstance(aSelector); factoryReference = locator.useBeanFactory(aFactoryName); } catch (BeansException e) { throw new BeanFactoryException( - "Could not load bean factory: selector = '" + aSelector - + "', factory = '" + aFactoryName + "'", e); + "Could not load bean factory: selector = '" + aSelector + + "', factory = '" + aFactoryName + "'", e); } } /* * (non-Javadoc) - * + * * @see org.wamblee.general.BeanFactory#find(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aId DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Object find(String aId) { return find(aId, Object.class); } /* * (non-Javadoc) - * + * * @see org.wamblee.general.BeanFactory#find(java.lang.Class) */ + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aClass DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public T find(Class aClass) { return find(aClass.getName(), aClass); } /* * (non-Javadoc) - * + * * @see org.wamblee.general.BeanFactory#find(java.lang.String, * java.lang.Class) */ + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aId DOCUMENT ME! + * @param aClass DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws BeanFactoryException DOCUMENT ME! + */ public T find(String aId, Class 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. + * Gets the spring bean factory. + * + * @return Spring bean factory. */ - public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() { - return factoryReference.getFactory(); + public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() { + return factoryReference.getFactory(); } - } diff --git a/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java b/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java index 003395d3..f6ee9c3b 100644 --- a/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java +++ b/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java @@ -1,46 +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.persistence.hibernate; import java.util.ArrayList; import java.util.Arrays; + /** - * Hibernate mapping files to use. + * Hibernate mapping files to use. * * @author Erik Brakkee */ public class HibernateMappingFiles extends ArrayList { - - /** +/** * Constructs an empty list of hibernate mapping files. * */ - public HibernateMappingFiles() { - super(); + public HibernateMappingFiles() { + super(); } - - /** + +/** * Constructs the list of Spring config files. * @param aFiles Files. */ - public HibernateMappingFiles(String[] aFiles) { - super(); + public HibernateMappingFiles(String[] aFiles) { + super(); addAll(Arrays.asList(aFiles)); } - } diff --git a/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java b/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java index 5012b02f..aa52f0d4 100644 --- a/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java +++ b/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java @@ -1,69 +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.persistence.hibernate; +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; + 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}. + * 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. - * + * DOCUMENT ME! */ - 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(); - } - } + private static final Log LOG = LogFactory.getLog(HibernateSupport.class); - /** +/** * Constructs the object. * */ @@ -72,30 +53,26 @@ public class HibernateSupport extends HibernateDaoSupport { } /** - * Performes a hibernate Session.merge() 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. + * Performes a hibernate Session.merge() 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. + * 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); @@ -103,79 +80,81 @@ public class HibernateSupport extends HibernateDaoSupport { } /** - * 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. + * 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. + * + * @throws RuntimeException DOCUMENT ME! */ public static void processPersistent(Persistent aPersistent, - Persistent aMerged, List aProcessed) { - if (aPersistent == null && aMerged == null) { + Persistent aMerged, List aProcessed) { + if ((aPersistent == null) && (aMerged == null)) { return; } - if (aPersistent == null || aMerged == null) { + + if ((aPersistent == null) || (aMerged == null)) { throw new RuntimeException("persistent or merged object is null '" - + aPersistent + "'" + " '" + aMerged + "'"); + + 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 + if ((aPersistent.getPrimaryKey() != null) && !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) { LOG.error("Mismatch between primary key values: " + aPersistent - + " " + aMerged); + + " " + 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 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 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 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); + 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); + && 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); + aProcessed); } } } catch (InvocationTargetException e) { @@ -185,58 +164,60 @@ public class HibernateSupport extends HibernateDaoSupport { } } } - } /** * 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. + * + * @param aPersistent Collection in the original object. + * @param aMerged Collection as a result of the merge. + * @param aProcessed List of processed persistent objects. + * + * @throws RuntimeException DOCUMENT ME! */ public static void processList(List aPersistent, List aMerged, - List aProcessed) { - Object[] merged = aMerged.toArray(); + List aProcessed) { + Object[] merged = aMerged.toArray(); Object[] persistent = aPersistent.toArray(); + if (merged.length != persistent.length) { throw new RuntimeException("Array sizes differ " + merged.length - + " " + persistent.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); + (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. + * + * @param aPersistent Collection in the original object. + * @param aMerged Collection as a result of the merge. + * @param aProcessed List of processed persistent objects. + * + * @throws RuntimeException DOCUMENT ME! */ public static void processSet(Set aPersistent, Set aMerged, - List aProcessed) { + List aProcessed) { if (aMerged.size() != aPersistent.size()) { throw new RuntimeException("Array sizes differ " + aMerged.size() - + " " + aPersistent.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); + (Persistent) merged, aProcessed); + break; } } @@ -245,37 +226,62 @@ public class HibernateSupport extends HibernateDaoSupport { /** * 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. + * + * @param aPersistent Collection in the original object. + * @param aMerged Collection as a result of the merge. + * @param aProcessed List of processed persistent objects. + * + * @throws RuntimeException DOCUMENT ME! */ public static void processMap(Map aPersistent, Map aMerged, - List aProcessed) { + List aProcessed) { if (aMerged.size() != aPersistent.size()) { throw new RuntimeException("Sizes differ " + aMerged.size() + " " - + aPersistent.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 mergedValue = aMerged.get(key); Object persistentValue = aPersistent.get(key); + if (mergedValue instanceof Persistent) { if (persistentValue instanceof Persistent) { processPersistent((Persistent) persistentValue, - (Persistent) mergedValue, aProcessed); + (Persistent) mergedValue, aProcessed); } else { throw new RuntimeException( - "Value in original object is null, whereas merged object contains a value"); + "Value in original object is null, whereas merged object contains a value"); } } } } + /** + * 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(); + } + } } diff --git a/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java b/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java index 9257f7d7..cb827f36 100644 --- a/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java +++ b/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java @@ -1,83 +1,99 @@ /* * 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; + /** - * + * DOCUMENT ME! * * @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); - } - } - + /** + * DOCUMENT ME! + */ private Runnable target; /* * (non-Javadoc) - * + * * @see org.wamblee.concurrency.AbstractLockTestCase#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { super.setUp(); - - Runner runner = new Runner(); - LockAdvice advice = new LockAdvice(new JvmLock()); - + + Runner runner = new Runner(); + LockAdvice advice = new LockAdvice(new JvmLock()); + ProxyFactoryBean support = new ProxyFactoryBean(); - support.setInterfaces(new Class[]{ Runnable.class }); + support.setInterfaces(new Class[] { Runnable.class }); support.setTarget(runner); support.addAdvice(advice); - target = (Runnable)support.getObject(); - + target = (Runnable) support.getObject(); } /* * (non-Javadoc) - * + * * @see org.wamblee.concurrency.AbstractLockTestCase#runThread() */ + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws RuntimeException DOCUMENT ME! + */ @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); - } - }; - }); + public void run() { + try { + getTracker().eventOccurred(STARTED); + target.run(); + getTracker().eventOccurred(RELEASED); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + ; + }); t.start(); + return t; } + private class Runner implements Runnable { + public void run() { + LockAdviceTest.this.getTracker().eventOccurred(ACQUIRED); + TimingUtils.sleep(SLEEP_TIME); + } + } } diff --git a/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java b/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java index 21bf1957..97254f1f 100644 --- a/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java +++ b/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java @@ -1,24 +1,24 @@ /* * 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 junit.framework.TestCase; + import org.wamblee.general.BeanFactoryException; -import junit.framework.TestCase; /** * Tests the spring bean factory. @@ -26,26 +26,34 @@ import junit.framework.TestCase; * @author Erik Brakkee */ public class SpringBeanFactoryTest extends TestCase { - /* * (non-Javadoc) - * + * * @see junit.framework.TestCase#setUp() */ + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { super.setUp(); - } + /** + * DOCUMENT ME! + */ public void testExistingBeanRefContext() { - SpringBeanFactory factory = new SpringBeanFactory( - "org/wamblee/general/beanRefContext.xml", "test"); + SpringBeanFactory factory = new SpringBeanFactory("org/wamblee/general/beanRefContext.xml", + "test"); - String value1 = factory.find(String.class); + 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); @@ -54,16 +62,21 @@ public class SpringBeanFactoryTest extends TestCase { } catch (BeanFactoryException e) { return; // ok } + fail(); } + /** + * DOCUMENT ME! + */ public void testUnknownBeanFactory() { try { - new SpringBeanFactory( - "org/wamblee/general/beanRefContext.xml", "unknown"); + new SpringBeanFactory("org/wamblee/general/beanRefContext.xml", + "unknown"); } catch (BeanFactoryException e) { return; // ok } + fail(); } } diff --git a/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java b/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java index e5e566ce..25354169 100644 --- a/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java +++ b/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java @@ -1,19 +1,18 @@ /* * 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; /** @@ -22,9 +21,10 @@ package org.wamblee.general.spring; * @author Erik Brakkee */ public class TestBeanFactory extends SpringBeanFactory { - - - public TestBeanFactory() { +/** + * Creates a new TestBeanFactory object. + */ + public TestBeanFactory() { super("org/wamblee/general/beanRefContext.xml", "test"); } } diff --git a/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java b/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java index aefe4185..ff5321ca 100644 --- a/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java +++ b/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java @@ -1,52 +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.test.spring; +import org.hibernate.cfg.Configuration; + +import org.hibernate.tool.hbm2ddl.SchemaExport; + import java.io.File; import java.io.IOException; -import org.hibernate.cfg.Configuration; -import org.hibernate.tool.hbm2ddl.SchemaExport; /** - * Exporting the hibernate mapping. + * Exporting the hibernate mapping. * * @author Erik Brakkee */ public final class HibernateExporter { - - /** +/** * Disabled constructor. * */ - private HibernateExporter() { + private HibernateExporter() { // Empty } - + + /** + * DOCUMENT ME! + * + * @param aArgs DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ 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); + 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.setOutputFile(file); export.create(true, false); } - } diff --git a/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java b/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java index 87219de0..cb78ea09 100644 --- a/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java +++ b/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java @@ -1,26 +1,27 @@ /* * 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.hibernate.cfg.Configuration; + +import org.hibernate.tool.hbm2ddl.SchemaUpdate; + import java.io.File; import java.io.IOException; -import org.hibernate.cfg.Configuration; -import org.hibernate.tool.hbm2ddl.SchemaUpdate; /** * Exporting the hibernate mapping. @@ -28,23 +29,28 @@ import org.hibernate.tool.hbm2ddl.SchemaUpdate; * @author Erik Brakkee */ public final class HibernateUpdater { - - /** +/** * Disabled constructor. * */ - private HibernateUpdater() { + private HibernateUpdater() { // Empty } + /** + * DOCUMENT ME! + * + * @param aArgs DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public static void main(String[] aArgs) throws IOException { - String file = aArgs[0]; - File dir = new File(file); + String file = aArgs[0]; + File dir = new File(file); - Configuration conf = HibernateUtils.getConfiguration(dir); + Configuration conf = HibernateUtils.getConfiguration(dir); - SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf); + SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf); lSchemaUpdate.execute(true, true); } - } diff --git a/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java b/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java index 74a7ef7e..0c6c8f54 100644 --- a/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java +++ b/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java @@ -1,32 +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.test.spring; +import org.apache.oro.io.AwkFilenameFilter; + +import org.hibernate.cfg.Configuration; + +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.InputResource; + 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. @@ -34,25 +37,34 @@ import org.wamblee.io.InputResource; * @author Erik Brakkee */ public final class HibernateUtils { - + /** + * DOCUMENT ME! + */ private static final String DATABASE_PROPS = "test.database.properties"; - /** +/** * Disabled. * */ - private HibernateUtils() { + private HibernateUtils() { // Empty } - + /** + * DOCUMENT ME! + * * @param aDir + * * @return + * + * @throws IOException DOCUMENT ME! */ - public static Configuration getConfiguration(File aDir) throws IOException { - Configuration conf = new Configuration(); - File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter( - ".*\\.hbm\\.xml"))); + 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); @@ -62,32 +74,37 @@ public final class HibernateUtils { for (Map.Entry entry : dbProps.entrySet()) { System.out.println("Property: " + entry.getKey() + "=" - + entry.getValue()); + + entry.getValue()); conf.setProperty(entry.getKey(), entry.getValue()); } return conf; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ private static Map getHibernateProperties() - throws IOException { - + throws IOException { System.out.println("Reading properties file: " + DATABASE_PROPS); + InputResource lPropFile = new ClassPathResource(DATABASE_PROPS); - Properties props = new Properties(); + Properties props = new Properties(); props.load(lPropFile.getInputStream()); Map result = new TreeMap(); - 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")); + 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/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java b/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java index d604e166..9016ee57 100644 --- a/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java +++ b/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java @@ -1,48 +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.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. + * Bean factory which uses Spring. * * @author Erik Brakkee */ public class TestSpringBeanFactory implements BeanFactory { - - private ApplicationContext context; - + /** + * DOCUMENT ME! + */ + private ApplicationContext context; + +/** + * Creates a new TestSpringBeanFactory object. + * + * @param aContext DOCUMENT ME! + */ public TestSpringBeanFactory(ApplicationContext aContext) { - context = aContext; + context = aContext; } /* (non-Javadoc) * @see org.wamblee.general.BeanFactory#find(java.lang.String) */ + /** + * DOCUMENT ME! + * + * @param aId DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Object find(String aId) { - return find(aId, Object.class); + return find(aId, Object.class); } /* (non-Javadoc) * @see org.wamblee.general.BeanFactory#find(java.lang.Class) */ + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aClass DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public T find(Class aClass) { return find(aClass.getName(), aClass); } @@ -50,14 +75,25 @@ public class TestSpringBeanFactory implements BeanFactory { /* (non-Javadoc) * @see org.wamblee.general.BeanFactory#find(java.lang.String, java.lang.Class) */ + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aId DOCUMENT ME! + * @param aClass DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws BeanFactoryException DOCUMENT ME! + */ public T find(String aId, Class aClass) { try { Object obj = context.getBean(aId, aClass); - assert obj != null; - return aClass.cast(obj); - } catch (BeansException e) { + assert obj != null; + + return aClass.cast(obj); + } catch (BeansException e) { throw new BeanFactoryException(e.getMessage(), e); } } - } diff --git a/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java b/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java index 37ea898b..7a2891bd 100644 --- a/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java +++ b/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java @@ -1,22 +1,23 @@ /* * 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. @@ -25,11 +26,13 @@ import java.util.Map; */ public interface TestTransactionCallback { /** - * Executes code within a transaction, causing the testcase to fail if any - * type of exception is thrown. - * + * 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. + * + * @throws Exception DOCUMENT ME! */ Map execute() throws Exception; } diff --git a/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java b/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java index a5011e48..05cc7838 100644 --- a/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java +++ b/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java @@ -1,18 +1,18 @@ /* * 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; /** @@ -23,9 +23,10 @@ package org.wamblee.test.spring; */ public interface TestTransactionCallbackWithoutResult { /** - * Executes code within a transaction, causing the testcase to fail if any - * type of exception is thrown. - * + * Executes code within a transaction, causing the testcase to fail + * if any type of exception is thrown. + * + * @throws Exception DOCUMENT ME! */ void execute() throws Exception; } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java b/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java index ace1525d..9d003c3f 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java @@ -1,12 +1,12 @@ /* * 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. @@ -20,37 +20,59 @@ 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 { + /** + * DOCUMENT ME! + */ + private ClassConfiguration _classConfig; + + /** + * Creates a new ClassAdapter object. + * + * @param aName DOCUMENT ME! + * @param aClassConfig DOCUMENT ME! + */ + public ClassAdapter(String aName, ClassConfiguration aClassConfig) { + super(aName, + aClassConfig.getProvidedInterfaces() + .toArray(new ProvidedInterface[0]), + aClassConfig.getRequiredInterfaces() + .toArray(new RequiredInterface[0])); + _classConfig = aClassConfig; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @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; + } - 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. - } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + protected void doStop(Object aRuntime) { + // Empty. + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java b/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java index a686f88c..1c8760bb 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,74 +15,110 @@ */ 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; +import java.util.ArrayList; +import java.util.List; + + /** - * The class configuration encapsulates the knowledge of how to wrap a class as a component. - * - * @author Erik Brakkee + * The class configuration encapsulates the knowledge of how to wrap a + * class as a component. * + * @author Erik Brakkee */ public class ClassConfiguration { + /** + * DOCUMENT ME! + */ + private Class _class; + + /** + * DOCUMENT ME! + */ + private ConstructorConfiguration constructorConfig; + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public ConstructorConfiguration getConstructorConfig() { + return constructorConfig; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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 aScope Scope in which injection takes place. + * @param aObject Object to inject into. + */ + public void inject(Scope aScope, Object aObject) { + objectConfig.inject(aScope, aObject); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public List getProvidedInterfaces() { + List result = new ArrayList(); + result.add(new DefaultProvidedInterface("provided", _class)); + + return result; + } - 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; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public List getRequiredInterfaces() { + List result = new ArrayList(); + result.addAll(constructorConfig.getRequiredInterfaces()); + result.addAll(objectConfig.getRequiredInterfaces()); - /** - * 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 getProvidedInterfaces() { - List result = new ArrayList(); - result.add(new DefaultProvidedInterface("provided", _class)); - return result; - } - - public List getRequiredInterfaces() { - List result = new ArrayList(); - result.addAll(constructorConfig.getRequiredInterfaces()); - result.addAll(objectConfig.getRequiredInterfaces()); - return result; - } + return result; + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java b/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java index 9050b955..d5256cc8 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java @@ -1,179 +1,218 @@ /* * 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.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; + 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: - *
    - *
  • Selection of a constructor using explicit selection - * {@link #select(Class...)} or using the most greedy constructor - * {@link #greedy()}. - *
  • - *
  • - * Selection of methods to invoke to inject other objects into the object. - *
  • - *
  • Selection of fields to set. - *
  • - *
+ * Class that allows configuration of the constructor to use. In + * particular, it provides: + *
    + *
  • Selection of a constructor using explicit selection {@link + * #select(Class...)} or using the most greedy constructor {@link + * #greedy()}.
  • + *
  • Selection of methods to invoke to inject other objects into + * the object.
  • + *
  • Selection of fields to set.
  • + *
*/ public class ConstructorConfiguration { - private Class clazz; - 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) { - clazz = 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 = clazz.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 = clazz.getDeclaredConstructors(); - if (declared.length == 0) { - throw new SystemAssemblyException("Class '" + clazz - + " is an interface, primitive type, or array"); - } - int max = -1; - List> checked = new ArrayList>(); - CollectionFilter.filter(Arrays.asList(declared), checked, - new Condition>() { - @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> ctors = checked; - List> longest = new ArrayList>(); - CollectionFilter.filter(ctors, longest, - new Condition>() { - @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[] valueArray = values.values(aScope); - try { - return getConstructor().newInstance(valueArray); - } catch (Exception e) { - throw new SystemAssemblyException("Could not construct object " - + getConstructor() + " " + Arrays.asList(valueArray), e); - } - } - - public List getRequiredInterfaces() { - getConstructor(); // initialize constructor if needed. - return values.getRequiredInterfaces(); - } - - private Constructor getConstructor() { - if (constructor == null ) { - greedy(); - } - return constructor; - } + /** + * DOCUMENT ME! + */ + private Class clazz; + + /** + * DOCUMENT ME! + */ + private Constructor constructor; + + /** + * DOCUMENT ME! + */ + private ParameterValues values; + + /** + * DOCUMENT ME! + */ + 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) { + clazz = 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. + * + * @return Return the injector to allow call chaining. + * + * @throws SystemAssemblyException DOCUMENT ME! + */ + public ConstructorConfiguration select(Class... aTypes) { + try { + constructor = clazz.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 = clazz.getDeclaredConstructors(); + + if (declared.length == 0) { + throw new SystemAssemblyException("Class '" + clazz + + " is an interface, primitive type, or array"); + } + + int max = -1; + List> checked = new ArrayList>(); + CollectionFilter.filter(Arrays.asList(declared), checked, + new Condition>() { + @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> ctors = checked; + List> longest = new ArrayList>(); + CollectionFilter.filter(ctors, longest, + new Condition>() { + @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. + * + * @throws SystemAssemblyException DOCUMENT ME! + */ + public Object create(Scope aScope) { + Object[] valueArray = values.values(aScope); + + try { + return getConstructor().newInstance(valueArray); + } catch (Exception e) { + throw new SystemAssemblyException("Could not construct object " + + getConstructor() + " " + Arrays.asList(valueArray), e); + } + } + + public List getRequiredInterfaces() { + getConstructor(); // initialize constructor if needed. + + return values.getRequiredInterfaces(); + } + + private Constructor getConstructor() { + if (constructor == null) { + greedy(); + } + + return constructor; + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java b/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java index 823b7c0d..59a6e7e0 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java @@ -1,12 +1,12 @@ /* * 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. @@ -20,41 +20,94 @@ import org.wamblee.system.core.Component; import org.wamblee.system.core.ProvidedInterface; import org.wamblee.system.core.RequiredInterface; -public class DefaultContainer extends Container { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class DefaultContainer extends Container { + /** + * Creates a new DefaultContainer object. + * + * @param aName DOCUMENT ME! + */ public DefaultContainer(String aName) { super(aName); } + /** + * DOCUMENT ME! + * + * @param aComponent DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public DefaultContainer addComponent(Component aComponent) { super.addComponent(aComponent); + return this; } - - public DefaultContainer addComponent(String aName, ClassConfiguration aConfiguration) { + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * @param aConfiguration DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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 + "'"); + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * @param aObject DOCUMENT ME! + * @param aConfiguration DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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)); } - + /** + * DOCUMENT ME! + * + * @param aRequired DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public DefaultContainer addRequiredInterface(RequiredInterface aRequired) { super.addRequiredInterface(aRequired); + return this; } + /** + * DOCUMENT ME! + * + * @param aProvided DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public DefaultContainer addProvidedInterface(ProvidedInterface aProvided) { super.addProvidedInterface(aProvided); + return this; } - } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java b/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java index 98fa48af..88500136 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java @@ -1,41 +1,51 @@ /* * 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; - } + /** + * DOCUMENT ME! + */ + 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; - } + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Object getValue(Scope aScope) { + return _value; + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java b/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java index f8259030..74120435 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java @@ -1,12 +1,12 @@ /* * 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. @@ -21,38 +21,67 @@ 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. - * + * An adapter class that adapts an existing object to a component. + * * @author Erik Brakkee */ public class ObjectAdapter extends AbstractComponent { + /** + * DOCUMENT ME! + */ + private ObjectConfiguration objectConfig; + + /** + * DOCUMENT ME! + */ + private Object object; + + /** + * Creates a new ObjectAdapter object. + * + * @param aName DOCUMENT ME! + * @param aObject DOCUMENT ME! + * @param aObjectConfig DOCUMENT ME! + */ + 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; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + protected Object doStart(Scope aScope) { + objectConfig.inject(aScope, object); + + for (ProvidedInterface provided : getProvidedInterfaces()) { + addInterface(provided, object, aScope); + } + + return 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. - } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + protected void doStop(Object aRuntime) { + // Empty. + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java b/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java index 0efa2275..a3bf37e1 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java @@ -1,61 +1,92 @@ /* * 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; + 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. - * + * General configuration for an instantiated object. + * * @author Erik Brakkee */ public class ObjectConfiguration { - - private Class _class; + /** + * DOCUMENT ME! + */ + private Class _class; + + /** + * DOCUMENT ME! + */ private SetterConfiguration setterConfig; - public ObjectConfiguration(Class aClass) { - _class = aClass; - setterConfig = new SetterConfiguration(aClass); + /** + * Creates a new ObjectConfiguration object. + * + * @param aClass DOCUMENT ME! + */ + 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. + * 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) { + public void inject(Scope aScope, Object aObject) { setterConfig.inject(aScope, aObject); } - - public SetterConfiguration getSetterConfig() { - return setterConfig; + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public SetterConfiguration getSetterConfig() { + return setterConfig; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public List getRequiredInterfaces() { List result = new ArrayList(); result.addAll(setterConfig.getRequiredInterfaces()); - return result; + + return result; } + /** + * DOCUMENT ME! + * + * @param aObject DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public boolean appliesTo(Object aObject) { return _class.isInstance(aObject); } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java b/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java index fa0f008e..4b561c3e 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java @@ -1,54 +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.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; +import java.util.ArrayList; +import java.util.List; + + /** - * Represents parameter values for a method or constructor and allows for the configuration - * of how these values are retrieved. - * + * 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(); - } - - /** + /** + * DOCUMENT ME! + */ + private String[] names; + + /** + * DOCUMENT ME! + */ + private Class[] types; + + /** + * DOCUMENT ME! + */ + 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. @@ -56,77 +70,95 @@ public class ParameterValues { * @param aClass Class to construct. */ public ParameterValues(String[] aNames, Class[] aTypes) { - assert aNames.length == aTypes.length; - names = aNames; - types = aTypes; - resetValues(); + 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. + * + * @return DOCUMENT ME! + */ + 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. + * + * @return DOCUMENT ME! + */ + 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 getRequiredInterfaces() { + List result = new ArrayList(); + + 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[] valueArray = new Object[values.length]; + + for (int i = 0; i < values.length; i++) { + valueArray[i] = values[i].getValue(aScope); + } + + return valueArray; } - - /** - * 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 getRequiredInterfaces() { - List result = new ArrayList(); - 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[] valueArray = new Object[values.length]; - for (int i = 0; i < values.length; i++) { - valueArray[i] = values[i].getValue(aScope); - } - return valueArray; - } - } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java b/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java index c6d70372..a0f09026 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java @@ -1,47 +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 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; - } + /** + * DOCUMENT ME! + */ + private RequiredInterface required; + +/** + * Constructs the provider + * @param aRequired Required interface. + */ + public RequiredInterfaceProvider(RequiredInterface aRequired) { + required = aRequired; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Object getValue(Scope aScope) { + return aScope.getInterfaceImplementation(required.getProvider(), + Object.class); + } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public RequiredInterface getRequiredInterface() { + return required; + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java b/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java index 77fd9720..d9c83bb4 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,22 +15,15 @@ */ 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; @@ -38,266 +31,351 @@ import org.wamblee.system.core.RequiredInterface; import org.wamblee.system.core.Scope; import org.wamblee.system.core.SystemAssemblyException; +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; + + /** - * Represents the configuration for exposing the setters of a class as required - * interfaces. - * + * Represents the configuration for exposing the setters of a class as + * required interfaces. + * * @author Erik Brakkee */ public class SetterConfiguration { + /** + * DOCUMENT ME! + */ + private Class _class; - private Class _class; - private boolean publicOnly; - - private Map 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(); - } - - /** - * 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)) { + /** + * DOCUMENT ME! + */ + private boolean publicOnly; + + /** + * DOCUMENT ME! + */ + private Map 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(); + } + + /** + * Makes sure that all available setters are used. + * + * @return DOCUMENT ME! + */ + 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. + * + * @return DOCUMENT ME! + */ + 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. + * + * @throws IllegalArgumentException DOCUMENT ME! + */ + public SetterConfiguration remove(String aName) { + for (Method method : setters.keySet()) { + if (method.getName().equals(aName)) { 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 methods = new ArrayList(); - CollectionFilter.filter(getAllSetters(_class, publicOnly), methods, - new Condition() { - @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 result = new ArrayList(); - CollectionFilter.filter(getAllSetters(_class, publicOnly), result, - new Condition() { - @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 getAllSetters(Class aClass, - boolean aPublicOnly) { - List result = new ArrayList(); - 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 getAllMethods(Class aClass) { - return ReflectionUtils.getAllMethods(aClass); - } - - /** - * Gets the required interfaces based on the configured setteres. - * - * @return List of required interfaces. - */ - public List getRequiredInterfaces() { - List result = new ArrayList(); - 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 getSetters() { - return new ArrayList(setters.keySet()); - } + "No method configured by the name of '" + aName + "'"); + } + + /** + * Removes the method from the set of methods. + * + * @param aMethod Method to remove. + * + * @return + * + * @throws RuntimeException DOCUMENT ME! + * @throws IllegalArgumentException DOCUMENT ME! + */ + 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. + * + * @throws IllegalArgumentException DOCUMENT ME! + */ + public SetterConfiguration add(final String aName) { + int oldlen = setters.size(); + List methods = new ArrayList(); + CollectionFilter.filter(getAllSetters(_class, publicOnly), methods, + new Condition() { + @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 result = new ArrayList(); + CollectionFilter.filter(getAllSetters(_class, publicOnly), result, + new Condition() { + @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. + * + * @param aClass DOCUMENT ME! + * @param aPublicOnly DOCUMENT ME! + * + * @return List of all setters. + */ + public static List getAllSetters(Class aClass, boolean aPublicOnly) { + List result = new ArrayList(); + + 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; + } + + /** + * DOCUMENT ME! + * + * @param aMethod DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + * + * @param aClass DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static final List getAllMethods(Class aClass) { + return ReflectionUtils.getAllMethods(aClass); + } + + /** + * Gets the required interfaces based on the configured setteres. + * + * @return List of required interfaces. + */ + public List getRequiredInterfaces() { + List result = new ArrayList(); + + 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. + * + * @throws IllegalArgumentException DOCUMENT ME! + * @throws SystemAssemblyException DOCUMENT ME! + */ + 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 aMethod Setter name without the "set" prefix with the first + * character converted to lower case. + * + * @return Parameter values. + * + * @throws IllegalArgumentException DOCUMENT ME! + */ + 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"); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public List getSetters() { + return new ArrayList(setters.keySet()); + } } diff --git a/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java b/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java index 6582f8fc..fe059a62 100644 --- a/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java +++ b/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java @@ -1,28 +1,35 @@ /* * 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); + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + Object getValue(Scope aScope); } diff --git a/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java b/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java index 48ef0e38..718432fc 100644 --- a/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java +++ b/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java @@ -1,70 +1,116 @@ /* * 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; +import java.io.IOException; + +import java.util.Properties; + + /** - * 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. - * + * 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 { - - private static ProvidedInterface PROPS = new DefaultProvidedInterface("props", Properties.class); - + /** + * DOCUMENT ME! + */ + private static ProvidedInterface PROPS = new DefaultProvidedInterface("props", + Properties.class); + + /** + * DOCUMENT ME! + */ 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; + + /** + * Creates a new PropertyComponent object. + * + * @param aName DOCUMENT ME! + * @param aResource DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + public PropertyComponent(String aName, InputResource aResource) + throws IOException { + this(aName, readProps(aResource)); } + /** + * Creates a new PropertyComponent object. + * + * @param aName DOCUMENT ME! + * @param aProps DOCUMENT ME! + */ public PropertyComponent(String aName, Properties aProps) { super(aName); - props = aProps; - + props = aProps; + addProvidedInterface(PROPS); } + /** + * DOCUMENT ME! + * + * @param aResource DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + private static Properties readProps(InputResource aResource) + throws IOException { + Properties props = new Properties(); + props.load(aResource.getInputStream()); + + return props; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected Properties doStart(Scope aScope) { addInterface(PROPS, props, aScope); - return props; + + return props; } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ @Override protected void doStop(Properties aRuntime) { // Empty } - } diff --git a/system/general/src/main/java/org/wamblee/system/container/Container.java b/system/general/src/main/java/org/wamblee/system/container/Container.java index cb7a0981..bb69712d 100644 --- a/system/general/src/main/java/org/wamblee/system/container/Container.java +++ b/system/general/src/main/java/org/wamblee/system/container/Container.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,13 +15,11 @@ */ 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; @@ -36,20 +34,38 @@ import org.wamblee.system.graph.component.ConnectExternalProvidedProvidedFilter; import org.wamblee.system.graph.component.ConnectRequiredExternallyRequiredEdgeFilter; import org.wamblee.system.graph.component.ConnectRequiredProvidedEdgeFilter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + + /** * Container consisting of multiple components. - * + * * @author Erik Brakkee */ public class Container extends AbstractComponent { - + /** + * DOCUMENT ME! + */ private static final Log LOG = LogFactory.getLog(Container.class); + /** + * DOCUMENT ME! + */ private List components; - private CompositeEdgeFilter edgeFilter; - private boolean sealed; /** + * DOCUMENT ME! + */ + private CompositeEdgeFilter edgeFilter; + + /** + * DOCUMENT ME! + */ + private boolean sealed; + +/** * Constructs the container * * @param aName @@ -62,18 +78,19 @@ public class Container extends AbstractComponent { * Required services by the container. */ public Container(String aName, Component[] aComponents, - List aProvided, List aRequired) { + List aProvided, List aRequired) { super(aName, aProvided, aRequired); - components = new ArrayList(); + components = new ArrayList(); + + edgeFilter = new CompositeEdgeFilter(); + sealed = false; - edgeFilter = new CompositeEdgeFilter(); - sealed = false; for (Component component : aComponents) { addComponent(component); } } - - /** + +/** * Constructs the container * * @param aName @@ -86,164 +103,244 @@ public class Container extends AbstractComponent { * Required services by the container. */ public Container(String aName, Component[] aComponents, - ProvidedInterface[] aProvided, RequiredInterface[] aRequired) { - this(aName, aComponents, Arrays.asList(aProvided), Arrays.asList(aRequired)); + ProvidedInterface[] aProvided, RequiredInterface[] aRequired) { + this(aName, aComponents, Arrays.asList(aProvided), + Arrays.asList(aRequired)); } + /** + * Creates a new Container object. + * + * @param aName DOCUMENT ME! + */ public Container(String aName) { this(aName, new Component[0], new ProvidedInterface[0], - new RequiredInterface[0]); + new RequiredInterface[0]); } + /** + * DOCUMENT ME! + * + * @param aComponent DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Container addComponent(Component aComponent) { checkSealed(); + if (aComponent.getContext() != null) { throw new SystemAssemblyException( - "Inconsistent hierarchy, component '" - + aComponent.getName() - + "' is already part of another hierarchy"); + "Inconsistent hierarchy, component '" + aComponent.getName() + + "' is already part of another hierarchy"); } - if ( findComponent(aComponent.getName()) != null ) { + + if (findComponent(aComponent.getName()) != null) { throw new SystemAssemblyException("Duplicate component '" - + aComponent.getName() + "'"); + + 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. + * 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. + * + * @throws SystemAssemblyException DOCUMENT ME! */ - public void connectRequiredProvided(String aClientComponent, String aRequiredInterface, - String aServerComponent, String aProvidedInterface) { + 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 (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 (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 (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 + "'"); - } + + 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)); + + 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). + * 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). + * + * @throws SystemAssemblyException DOCUMENT ME! */ - public void connectExternalRequired(String aComponent, String aRequiredInterface, - String aExternalRequiredInterface) { + 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 (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 (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 + "'"); - } + + 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) { + + /** + * DOCUMENT ME! + * + * @param aExternalProvided DOCUMENT ME! + * @param aComponent DOCUMENT ME! + * @param aProvidedInterface DOCUMENT ME! + */ + 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 (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 (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 + "'"); - } + + 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)); - } + edgeFilter.add(new ConnectExternalProvidedProvidedFilter( + aExternalProvided, aComponent, aProvidedInterface)); + } + /** + * DOCUMENT ME! + * + * @param aProvided DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public Container addProvidedInterface(ProvidedInterface aProvided) { checkSealed(); super.addProvidedInterface(aProvided); + return this; } + /** + * DOCUMENT ME! + * + * @param aRequired DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public Container addRequiredInterface(RequiredInterface aRequired) { checkSealed(); super.addRequiredInterface(aRequired); + return this; } + /** + * DOCUMENT ME! + * + * @param aContext DOCUMENT ME! + */ @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. + * 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. */ public void validate() { doStartOptionalDryRun(null, true); } /** - * Seal the container, meaning that no further components or interfaces may - * be added. + * Seal the container, meaning that no further components or + * interfaces may be added. */ public void seal() { sealed = true; @@ -251,7 +348,7 @@ public class Container extends AbstractComponent { /** * Checks if the container is sealed. - * + * * @return True iff the container is sealed. */ public boolean isSealed() { @@ -259,35 +356,63 @@ public class Container extends AbstractComponent { } /** - * Utility method to start with an empty external scope. This is useful for - * top-level containers which are not part of another container. - * + * 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); } + /** + * DOCUMENT ME! + * + * @param aExternalScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected Scope doStart(Scope aExternalScope) { validate(); - Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope); + + 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 mapping: - aGraph.findExternalProvidedInterfaceMapping()) { - Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class); + /** + * DOCUMENT ME! + * + * @param aGraph DOCUMENT ME! + * @param aExternalScope DOCUMENT ME! + * @param aInternalScope DOCUMENT ME! + */ + private void exposeProvidedInterfaces(ComponentGraph aGraph, + Scope aExternalScope, Scope aInternalScope) { + for (Pair mapping : aGraph + .findExternalProvidedInterfaceMapping()) { + Object svc = aInternalScope.getInterfaceImplementation(mapping + .getSecond(), Object.class); addInterface(mapping.getFirst(), svc, aExternalScope); } } + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * @param aDryRun DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) { ComponentGraph graph = createComponentGraph(); graph.validate(); @@ -296,6 +421,7 @@ public class Container extends AbstractComponent { LOG.info("Starting '" + getQualifiedName() + "'"); List started = new ArrayList(); + for (Component component : components) { try { // Start the service. @@ -308,32 +434,48 @@ public class Container extends AbstractComponent { throw e; } catch (RuntimeException e) { LOG.error(getQualifiedName() + ": could not start '" - + component.getQualifiedName() + "'", e); + + component.getQualifiedName() + "'", e); stopAlreadyStartedComponents(started, aScope); throw e; } } + return graph; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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()) { + + for (ProvidedInterface prov : getProvidedInterfaces()) { graph.addProvidedInterface(this, prov); } graph.addEdgeFilter(edgeFilter); + return graph; } + /** + * DOCUMENT ME! + * + * @param aStarted DOCUMENT ME! + * @param aScope DOCUMENT ME! + */ private void stopAlreadyStartedComponents(List aStarted, - Scope aScope) { + Scope aScope) { // an exception occurred, stop the successfully started // components for (int i = aStarted.size() - 1; i >= 0; i--) { @@ -342,46 +484,69 @@ public class Container extends AbstractComponent { aStarted.get(i).stop(aScope.getRuntime(component)); } catch (Throwable t) { LOG.error(getQualifiedName() + ": error stopping " - + aStarted.get(i).getQualifiedName()); + + aStarted.get(i).getQualifiedName()); } } } + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + */ @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); + Object runtime = aScope.getRuntime(component); component.stop(runtime); } } + /** + * DOCUMENT ME! + */ 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. + * 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; + public Component findComponent(String aName) { + for (Component component : components) { + if (component.getName().equals(aName)) { + return component; + } + } + + return null; } - - private static T findInterface(List aInterfaces, String aInterfaceName) { - for (T intf: aInterfaces) { - if ( intf.getName().equals(aInterfaceName)) { - return intf; - } - } - return null; + + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aInterfaces DOCUMENT ME! + * @param aInterfaceName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static T findInterface( + List aInterfaces, String aInterfaceName) { + for (T intf : aInterfaces) { + if (intf.getName().equals(aInterfaceName)) { + return intf; + } + } + + return null; } } diff --git a/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java b/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java index 579fd274..1ac464d0 100644 --- a/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java +++ b/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,48 +15,71 @@ */ package org.wamblee.system.core; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + 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. + * + * @param DOCUMENT ME! */ public abstract class AbstractComponent implements Component { + /** + * DOCUMENT ME! + */ + private static final Log LOG = LogFactory.getLog(AbstractComponent.class); - private static final Log LOG = LogFactory.getLog(AbstractComponent.class); - - private ThreadLocal> remaining; - - private String context; - private String name; - private List provided; - private List required; - - /** - * Constructs the subsystem. - * - * @param aName - * Name of the system. - * @param aProvided - * Provided services. - * @param aRequired - * Required services. - */ - protected AbstractComponent(String aName, List aProvided, - List aRequired) { - remaining = new ThreadLocal>(); - context = null; - name = aName; - provided = new ArrayList(aProvided); - required = new ArrayList(aRequired); - } - - /** + /** + * DOCUMENT ME! + */ + private ThreadLocal> remaining; + + /** + * DOCUMENT ME! + */ + private String context; + + /** + * DOCUMENT ME! + */ + private String name; + + /** + * DOCUMENT ME! + */ + private List provided; + + /** + * DOCUMENT ME! + */ + private List required; + +/** + * Constructs the subsystem. + * + * @param aName + * Name of the system. + * @param aProvided + * Provided services. + * @param aRequired + * Required services. + */ + protected AbstractComponent(String aName, + List aProvided, List aRequired) { + remaining = new ThreadLocal>(); + context = null; + name = aName; + provided = new ArrayList(aProvided); + required = new ArrayList(aRequired); + } + +/** * Constructs the subsystem. * * @param aName @@ -67,147 +90,252 @@ public abstract class AbstractComponent implements Component { * Required services. */ protected AbstractComponent(String aName, ProvidedInterface[] aProvided, - RequiredInterface[] aRequired) { + RequiredInterface[] aRequired) { this(aName, Arrays.asList(aProvided), Arrays.asList(aRequired)); } - - protected AbstractComponent(String aName) { - this(aName, new ProvidedInterface[0], new RequiredInterface[0]); - } - - public AbstractComponent addProvidedInterface(ProvidedInterface aProvided) { - provided.add(aProvided); - return this; - } - - public AbstractComponent 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 getProvidedInterfaces() { - return Collections.unmodifiableList(provided); - } - - @Override - public final List getRequiredInterfaces() { - return Collections.unmodifiableList(required); - } - - @Override - public final Type start(Scope aScope) { - LOG.info("Initialization starting '" + getQualifiedName() + "'"); - List oldRemaining = remaining.get(); - remaining.set(new ArrayList(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; - } + /** + * Creates a new AbstractComponent object. + * + * @param aName DOCUMENT ME! + */ + protected AbstractComponent(String aName) { + this(aName, new ProvidedInterface[0], new RequiredInterface[0]); + } + + /** + * DOCUMENT ME! + * + * @param aProvided DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public AbstractComponent addProvidedInterface( + ProvidedInterface aProvided) { + provided.add(aProvided); + + return this; + } + + /** + * DOCUMENT ME! + * + * @param aRequired DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public AbstractComponent addRequiredInterface( + RequiredInterface aRequired) { + required.add(aRequired); + + return this; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public final String getName() { + return name; + } + + /** + * DOCUMENT ME! + * + * @param aContext DOCUMENT ME! + */ + @Override + public void addContext(String aContext) { + if (context == null) { + context = aContext; + } else { + context = aContext + "." + context; + } + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getContext() { + return context; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getQualifiedName() { + if (context == null) { + return getName(); + } + + return context + "." + getName(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public final List getProvidedInterfaces() { + return Collections.unmodifiableList(provided); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public final List getRequiredInterfaces() { + return Collections.unmodifiableList(required); + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public final Type start(Scope aScope) { + LOG.info("Initialization starting '" + getQualifiedName() + "'"); + + List oldRemaining = remaining.get(); + remaining.set(new ArrayList(getProvidedInterfaces())); + + try { + Type runtime = doStart(aScope); + checkNotStartedInterfaces(); + LOG.info("Initialization finished '" + getQualifiedName() + "'"); + + return runtime; + } finally { + remaining.set(oldRemaining); + } + } + + /** + * DOCUMENT ME! + */ + 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. + * + * @param aScope DOCUMENT ME! + * + * @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. + * + * @throws SystemAssemblyException DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + public void stop(Type aRuntime) { + LOG.info("Stopping initiated '" + getQualifiedName() + "'"); + doStop(aRuntime); + LOG.info("Stopping completed '" + getQualifiedName() + "'"); + } + + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + protected abstract void doStop(Type aRuntime); + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String toString() { + return getQualifiedName(); + } + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public ProvidedInterface findProvidedInterface(String aName) { + for (ProvidedInterface provided : getProvidedInterfaces()) { + if (provided.getName().equals(aName)) { + return provided; + } + } + + return null; + } + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public RequiredInterface findRequiredInterface(String aName) { + for (RequiredInterface required : getRequiredInterfaces()) { + if (required.getName().equals(aName)) { + return required; + } + } + + return null; + } } diff --git a/system/general/src/main/java/org/wamblee/system/core/Component.java b/system/general/src/main/java/org/wamblee/system/core/Component.java index 9506bb1f..e70baa23 100644 --- a/system/general/src/main/java/org/wamblee/system/core/Component.java +++ b/system/general/src/main/java/org/wamblee/system/core/Component.java @@ -1,22 +1,23 @@ /* * 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. @@ -32,57 +33,84 @@ import java.util.List; * @author Erik Brakkee */ public interface Component { - - /** - * 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 the name of the subsystem. + * + * @return Subsystem name. + */ + String getName(); + + /** + * Prepends the context with a super context. + * + * @param aContext DOCUMENT ME! + */ + 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(); + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * Gets a description of the provided interfaces. + * @return Provided interfaces. + */ + List getProvidedInterfaces(); + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * Gets a description of the required interfaces. + * @return Required interfaces. + */ + List getRequiredInterfaces(); - /** - * Gets a description of the provided interfaces. - * @return Provided interfaces. - */ - List getProvidedInterfaces(); - - /** - * Gets a description of the required interfaces. - * @return Required interfaces. - */ - List 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); - - /** - * 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); + /** + * Stops a component. + * + * @param aRuntime THe runtime part of the component. + */ + void stop(Type aRuntime); } diff --git a/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java b/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java index d30a8c15..484f63a0 100644 --- a/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java +++ b/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java @@ -1,18 +1,18 @@ /* * 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; @@ -27,81 +27,141 @@ import java.util.List; * @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 result = new ArrayList(); - for (Class cls: interfaces) { - result.add(cls.getName()); - } - Collections.sort(result); - String value = ""; - for (String str: result) { - value += ":" + str; - } - return value; - } + /** + * DOCUMENT ME! + */ + private String name; + + /** + * DOCUMENT ME! + */ + private Class[] interfaces; + +/** + * Constructs the descriptor. + * @param aInterface Type of service. + */ + public DefaultProvidedInterface(String aName, Class aInterface) { + this(aName, new Class[] { aInterface }); + } + +/** + * Creates a new DefaultProvidedInterface object. + * + * @param aName DOCUMENT ME! + * @param aInterfaces DOCUMENT ME! + */ + public DefaultProvidedInterface(String aName, Class[] aInterfaces) { + name = aName; + interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getName() { + return name; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Class[] getInterfaceTypes() { + return interfaces; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append(getName()); + buf.append(":"); + + for (Class intf : interfaces) { + buf.append(" " + intf.getName()); + } + + return buf.toString(); + } + + /** + * DOCUMENT ME! + * + * @param aObj DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean equals(Object aObj) { + return this == aObj; + + /* + if ( !(aObj instanceof DefaultProvidedInterface)) { + return false; + } + DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj; + return getEqualsRepresentation().equals(provided.getEqualsRepresentation()); + */ + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public int hashCode() { + return getEqualsRepresentation().hashCode(); + } + + /** + * DOCUMENT ME! + * + * @param aInterface DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean covers(ProvidedInterface aInterface) { + // TODO do more than just equals. + if (!(aInterface instanceof DefaultProvidedInterface)) { + return false; + } + + return getEqualsRepresentation() + .equals(((DefaultProvidedInterface) aInterface).getEqualsRepresentation()); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private String getEqualsRepresentation() { + List result = new ArrayList(); + + for (Class cls : interfaces) { + result.add(cls.getName()); + } + + Collections.sort(result); + + String value = ""; + + for (String str : result) { + value += (":" + str); + } + + return value; + } } diff --git a/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java b/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java index 80c3d135..d47b6f49 100644 --- a/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java +++ b/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java @@ -1,142 +1,256 @@ /* * 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 org.wamblee.reflection.ReflectionUtils; + import java.util.Arrays; -import org.wamblee.reflection.ReflectionUtils; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DefaultRequiredInterface implements RequiredInterface { + /** + * DOCUMENT ME! + */ + private String name; + + /** + * DOCUMENT ME! + */ + private boolean optional; + + /** + * DOCUMENT ME! + */ + private Class[] required; + + /** + * DOCUMENT ME! + */ + private ProvidedInterface provider; + +/** + * Creates a new DefaultRequiredInterface object. + * + * @param aName DOCUMENT ME! + * @param aInterface DOCUMENT ME! + */ + public DefaultRequiredInterface(String aName, Class aInterface) { + this(aName, new Class[] { aInterface }); + } + +/** + * Creates a new DefaultRequiredInterface object. + * + * @param aName DOCUMENT ME! + * @param aInterfaces DOCUMENT ME! + */ + public DefaultRequiredInterface(String aName, Class[] aInterfaces) { + this(aName, aInterfaces, false); + } + +/** + * Creates a new DefaultRequiredInterface object. + * + * @param aName DOCUMENT ME! + * @param aInterface DOCUMENT ME! + * @param aIsOptional DOCUMENT ME! + */ + public DefaultRequiredInterface(String aName, Class aInterface, + boolean aIsOptional) { + this(aName, new Class[] { aInterface }, aIsOptional); + } + +/** + * Creates a new DefaultRequiredInterface object. + * + * @param aName DOCUMENT ME! + * @param aInterfaces DOCUMENT ME! + * @param aIsOptional DOCUMENT ME! + */ + public DefaultRequiredInterface(String aName, Class[] aInterfaces, + boolean aIsOptional) { + name = aName; + optional = aIsOptional; + required = aInterfaces; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getName() { + return name; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean isOptional() { + return optional; + } + + /** + * DOCUMENT ME! + * + * @param aDescriptor DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean implementedBy(ProvidedInterface aDescriptor) { + Class[] provided = aDescriptor.getInterfaceTypes(); + + for (Class requiredIntf : required) { + if (!serviceProvided(requiredIntf, 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; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public ProvidedInterface getProvider() { + return provider; + } + + /** + * DOCUMENT ME! + * + * @param aProvider DOCUMENT ME! + */ + @Override + public void setProvider(ProvidedInterface aProvider) { + assert aProvider != null; + assert implementedBy(aProvider); + provider = aProvider; + } + + /** + * DOCUMENT ME! + * + * @param obj DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean equals(Object obj) { + return this == obj; + } + + /** + * DOCUMENT ME! + * + * @param obj DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @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); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public int hashCode() { + return required.hashCode(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("." + getName() + ":"); + + for (Class intf : required) { + buf.append("." + intf.getName()); + } - 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 requiredIntf : required) { - if ( !serviceProvided(requiredIntf, 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(); - } + return buf.toString(); + } } diff --git a/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java b/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java index 3e15ea9c..7cfd2cab 100644 --- a/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java +++ b/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java @@ -1,12 +1,12 @@ /* * 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. @@ -22,90 +22,194 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DefaultScope implements Scope { + /** + * DOCUMENT ME! + */ + private List parents; + + /** + * DOCUMENT ME! + */ + private Map properties; + + /** + * DOCUMENT ME! + */ + private Map runtimes; + + /** + * DOCUMENT ME! + */ + private Map provided; + + /** + * DOCUMENT ME! + */ + private List externallyProvided; + +/** + * Creates a new DefaultScope object. + * + * @param aExternallyProvided DOCUMENT ME! + */ + public DefaultScope(List aExternallyProvided) { + this(aExternallyProvided.toArray(new ProvidedInterface[0])); + } + +/** + * Creates a new DefaultScope object. + * + * @param aExternallyProvided DOCUMENT ME! + */ + public DefaultScope(ProvidedInterface[] aExternallyProvided) { + this(aExternallyProvided, new ArrayList()); + } + +/** + * Creates a new DefaultScope object. + * + * @param aExternallyProvided DOCUMENT ME! + * @param aParent DOCUMENT ME! + */ + public DefaultScope(ProvidedInterface[] aExternallyProvided, Scope aParent) { + this(aExternallyProvided, Arrays.asList(new Scope[] { aParent })); + } + +/** + * Creates a new DefaultScope object. + * + * @param aExternallyProvided DOCUMENT ME! + * @param aParent DOCUMENT ME! + */ + public DefaultScope(ProvidedInterface[] aExternallyProvided, + List aParent) { + parents = new ArrayList(aParent); + properties = new HashMap(); + runtimes = new HashMap(); + provided = new HashMap(); + externallyProvided = new ArrayList(); + externallyProvided.addAll(Arrays.asList(aExternallyProvided)); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public List getProvidedInterfaces() { + return Collections.unmodifiableList(externallyProvided); + } + + /** + * DOCUMENT ME! + * + * @param aKey DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Object get(String aKey) { + return properties.get(aKey); + } + + /** + * DOCUMENT ME! + * + * @param aKey DOCUMENT ME! + * @param aValue DOCUMENT ME! + */ + @Override + public void put(String aKey, Object aValue) { + properties.put(aKey, aValue); + } + + /** + * DOCUMENT ME! + * + * @param aComponent DOCUMENT ME! + * @param aRuntime DOCUMENT ME! + */ + @Override + public void addRuntime(Component aComponent, Object aRuntime) { + runtimes.put(aComponent.getName(), aRuntime); + } + + /** + * DOCUMENT ME! + * + * @param aComponent DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Object getRuntime(Component aComponent) { + return runtimes.get(aComponent.getName()); + } + + /** + * DOCUMENT ME! + * + * @param aName DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Object getRuntime(String aName) { + return runtimes.get(aName); + } + + /** + * DOCUMENT ME! + * + * @param aInterface DOCUMENT ME! + * @param aImplementation DOCUMENT ME! + */ + @Override + synchronized public void publishInterface(ProvidedInterface aInterface, + Object aImplementation) { + provided.put(aInterface, + new ProvidedInterfaceImplementation(aInterface, aImplementation)); + } + + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aInterface DOCUMENT ME! + * @param aType DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public T getInterfaceImplementation(ProvidedInterface aInterface, + Class aType) { + if (aInterface == null) { + return null; + } + + ProvidedInterfaceImplementation providedIntf = provided.get(aInterface); + + if (providedIntf == null) { + for (Scope parent : parents) { + T impl = parent.getInterfaceImplementation(aInterface, aType); + + if (impl != null) { + return impl; + } + } - private List parents; - private Map properties; - private Map runtimes; - private Map provided; - private List externallyProvided; - - public DefaultScope(ListaExternallyProvided) { - this(aExternallyProvided.toArray(new ProvidedInterface[0])); - } - - public DefaultScope(ProvidedInterface[] aExternallyProvided) { - this(aExternallyProvided, new ArrayList()); - } - - public DefaultScope(ProvidedInterface[] aExternallyProvided, Scope aParent) { - this(aExternallyProvided, Arrays.asList(new Scope[] { aParent })); - } - - public DefaultScope(ProvidedInterface[] aExternallyProvided, - List aParent) { - parents = new ArrayList(aParent); - properties = new HashMap(); - runtimes = new HashMap(); - provided = new HashMap(); - externallyProvided = new ArrayList(); - externallyProvided.addAll(Arrays.asList(aExternallyProvided)); - } - - @Override - public List 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 getInterfaceImplementation(ProvidedInterface aInterface, - Class aType) { - if ( aInterface == null ) { - return null; - } - ProvidedInterfaceImplementation providedIntf = provided.get(aInterface); - if (providedIntf == null) { - for (Scope parent : parents) { - T impl = parent.getInterfaceImplementation(aInterface, aType); - if ( impl != null ) { - return impl; - } - } - return null; - } else { - return providedIntf.getImplementation(aType); - } - } + return null; + } else { + return providedIntf.getImplementation(aType); + } + } } diff --git a/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java b/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java index 9800621e..69c7a227 100644 --- a/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java +++ b/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java @@ -1,23 +1,31 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision: 1.6 $ + */ public interface NamedInterface { /** - * Name for the interface. + * Name for the interface. + * + * @return DOCUMENT ME! */ String getName(); } diff --git a/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java b/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java index f09a5270..34c8da05 100644 --- a/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java +++ b/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java @@ -1,22 +1,23 @@ /* * 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! @@ -24,19 +25,22 @@ import java.util.Collection; * @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); + /** + * 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/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java b/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java index abeb70d5..998e8d6b 100644 --- a/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java +++ b/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java @@ -1,53 +1,65 @@ /* * 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. - * + * Represents a provided interface together with its implementation. + * * @author Erik Brakkee */ class ProvidedInterfaceImplementation { + /** + * DOCUMENT ME! + */ + private ProvidedInterface _provided; + + /** + * DOCUMENT ME! + */ + private Object _implementation; + +/** + * Constructs the object. + * @param aProvided Provided interface. + * @param aImplementation Implementation. + */ + public ProvidedInterfaceImplementation(ProvidedInterface aProvided, + Object aImplementation) { + _provided = aProvided; + _implementation = aImplementation; + } - 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; - } + /** + * DOCUMENT ME! + * + * @return The provided interface. + */ + public ProvidedInterface getProvided() { + return _provided; + } - /** - * @return The provided interface. - */ - public ProvidedInterface getProvided() { - return _provided; - } - - /** - * @param Expected type of the implementation. - * @param aType Type of the implementation. - * @return Implementation. - */ - public T getImplementation(Class aType) { - return (T)_implementation; - } + /** + * DOCUMENT ME! + * + * @param Expected type of the implementation. + * @param aType Type of the implementation. + * + * @return Implementation. + */ + public T getImplementation(Class aType) { + return (T) _implementation; + } } diff --git a/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java b/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java index 4dd77fc7..e689352a 100644 --- a/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java +++ b/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java @@ -1,50 +1,64 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision: 1.6 $ + */ 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); + /** + * DOCUMENT ME! + * + * @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. + * + * @param aInterface DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + boolean covers(RequiredInterface aInterface); } diff --git a/system/general/src/main/java/org/wamblee/system/core/Scope.java b/system/general/src/main/java/org/wamblee/system/core/Scope.java index fe83e857..fedc99e6 100644 --- a/system/general/src/main/java/org/wamblee/system/core/Scope.java +++ b/system/general/src/main/java/org/wamblee/system/core/Scope.java @@ -1,22 +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; 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 @@ -25,62 +26,82 @@ import java.util.List; * @author Erik Brakkee */ public interface Scope { - - /** - * Gets the provided interfaces by this scope. - * @return Provided interfaces. - */ - List 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 getInterfaceImplementation(ProvidedInterface aProvided, Class aType ); + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** + * Gets the provided interfaces by this scope. + * @return Provided interfaces. + */ + List 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); + + /** + * DOCUMENT ME! + * + * @param DOCUMENT ME! + * @param aProvided DOCUMENT ME! + * @param aType DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + T getInterfaceImplementation(ProvidedInterface aProvided, Class 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. - * @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); + /** + * 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/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java b/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java index a8a0ac16..64f35e54 100644 --- a/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java +++ b/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java @@ -1,18 +1,18 @@ /* * 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; /** @@ -21,21 +21,20 @@ package org.wamblee.system.core; * @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. - */ - public SystemAssemblyException(String aMsg) { - super(aMsg); - } - - /** - * Constructs the exception. - * @param aMsg Message - * @param aCause Cause. - */ - public SystemAssemblyException(String aMsg, Throwable aCause) { - super(aMsg, aCause); - } +/** + * Constructs the exception. + * @param aMsg Message + * @param aCause Cause. + */ + public SystemAssemblyException(String aMsg, Throwable aCause) { + super(aMsg, aCause); + } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java b/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java index b919e908..89dfe7de 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java +++ b/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java @@ -1,43 +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; import java.util.ArrayList; import java.util.List; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class CompositeEdgeFilter implements EdgeFilter { - - private List filters; - - public CompositeEdgeFilter() { + /** + * DOCUMENT ME! + */ + private List filters; + + /** + * Creates a new CompositeEdgeFilter object. + */ + public CompositeEdgeFilter() { filters = new ArrayList(); } - - public void add(EdgeFilter aFilter) { + + /** + * DOCUMENT ME! + * + * @param aFilter DOCUMENT ME! + */ + public void add(EdgeFilter aFilter) { filters.add(aFilter); } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean isViolated(Edge aEdge) { - for (EdgeFilter filter: filters) { - if ( filter.isViolated(aEdge) ) { - return true; + for (EdgeFilter filter : filters) { + if (filter.isViolated(aEdge)) { + return true; } } - return false; - } + return false; + } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java b/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java index 29220498..44e9d522 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java +++ b/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java @@ -1,50 +1,75 @@ /* * 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. - * + * 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; + /** + * DOCUMENT ME! + */ + private Node from; + + /** + * DOCUMENT ME! + */ + private Node to; + + /** + * Creates a new DefaultEdge object. + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + */ + public DefaultEdge(Node aFrom, Node aTo) { + from = aFrom; + to = aTo; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public Node getFrom() { return from; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public Node getTo() { - return to; + return to; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return "Edge(" + from.getName() + ", " + to.getName() + ")"; } - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java b/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java index df61e97e..6d70d646 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java +++ b/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java @@ -1,55 +1,73 @@ /* * 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 + * 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; - /** + * DOCUMENT ME! + */ + private String name; + +/** * Constructs the node. * @param aName Node name. */ - public DefaultNode(String aName) { - name = aName; + public DefaultNode(String aName) { + name = aName; } /** - * Returns the node name. + * Returns the node name. + * + * @return DOCUMENT ME! */ @Override public String getName() { return name; } + /** + * DOCUMENT ME! + * + * @param aObj DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean equals(Object aObj) { - if ( !(aObj instanceof Node)) { - return false; + if (!(aObj instanceof Node)) { + return false; } - Node node = (Node)aObj; + + Node node = (Node) aObj; + return name.equals(node.getName()); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public int hashCode() { return name.hashCode(); diff --git a/system/general/src/main/java/org/wamblee/system/graph/Edge.java b/system/general/src/main/java/org/wamblee/system/graph/Edge.java index a340015a..8b56984e 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/Edge.java +++ b/system/general/src/main/java/org/wamblee/system/graph/Edge.java @@ -1,18 +1,18 @@ /* * 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; /** @@ -21,14 +21,19 @@ package org.wamblee.system.graph; * @author Erik Brakkee */ public interface Edge { - /** - * @return The from part of the edge. + * + DOCUMENT ME! + * + * @return The from part of the edge. */ Node getFrom(); - + /** - * @return The to part of the edge. + * + DOCUMENT ME! + * + * @return The to part of the edge. */ Node getTo(); } diff --git a/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java b/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java index 4ac39f6f..d54c896e 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java +++ b/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java @@ -1,22 +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.graph; import java.util.List; + /** * Edge factory used to extend a graph with new edges. * @author Erik Brakkee @@ -25,10 +26,18 @@ import java.util.List; */ public interface EdgeFactory { /** + * DOCUMENT ME! + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + * + * @return DOCUMENT ME! + */ +/** * 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 create(NodeType aFrom, NodeType aTo); + List create(NodeType aFrom, NodeType aTo); } diff --git a/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java b/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java index b372f082..e9771752 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java +++ b/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java @@ -1,21 +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.graph; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision: 1.6 $ + */ public interface EdgeFilter { - - boolean isViolated(Edge aEdge); + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + boolean isViolated(Edge aEdge); } diff --git a/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java b/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java index fca26ffb..92504690 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java +++ b/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java @@ -1,37 +1,65 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + * + * @param DOCUMENT ME! + * @param DOCUMENT ME! + */ public class EdgeSelector { - - public static interface Selector { - void execute(FromType aFrom, ToType aTo); - } - - private Class fromType; + /** + * DOCUMENT ME! + */ + private Class fromType; + + /** + * DOCUMENT ME! + */ private Class toType; - + + /** + * Creates a new EdgeSelector object. + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + */ public EdgeSelector(Class aFrom, Class aTo) { - fromType = aFrom; - toType = aTo; + fromType = aFrom; + toType = aTo; } - public void execute(Selector aSelector, Edge aEdge) { - if ( fromType.isInstance(aEdge.getFrom()) && toType.isInstance(aEdge.getTo())) { - aSelector.execute((FromType)aEdge.getFrom(), (ToType)aEdge.getTo()); - } + /** + * DOCUMENT ME! + * + * @param aSelector DOCUMENT ME! + * @param aEdge DOCUMENT ME! + */ + public void execute(Selector aSelector, Edge aEdge) { + if (fromType.isInstance(aEdge.getFrom()) + && toType.isInstance(aEdge.getTo())) { + aSelector.execute((FromType) aEdge.getFrom(), (ToType) aEdge.getTo()); + } + } + + public static interface Selector { + void execute(FromType aFrom, ToType aTo); } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/Graph.java b/system/general/src/main/java/org/wamblee/system/graph/Graph.java index ddfd2cf7..f84873e3 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/Graph.java +++ b/system/general/src/main/java/org/wamblee/system/graph/Graph.java @@ -1,12 +1,12 @@ /* * 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. @@ -19,46 +19,53 @@ 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 { - + /** + * DOCUMENT ME! + */ private List nodes; - private List edges; /** + * DOCUMENT ME! + */ + private List edges; + +/** * Constructs the graph. */ public Graph() { - nodes = new ArrayList(); - edges = new ArrayList(); + nodes = new ArrayList(); + edges = new ArrayList(); } /** * Adds a node. - * - * @param aNode - * Node to add. - * @throws IllegalArgumentException - * In case the node already exists. Node equality is checked - * using equals. + * + * @param aNode Node to add. + * + * @throws IllegalArgumentException In case the node already exists. Node + * equality is checked using equals. */ public void addNode(Node aNode) { if (nodes.contains(aNode)) { throw new IllegalArgumentException("Node '" + aNode.getName() - + "' already exists"); + + "' already exists"); } + nodes.add(aNode); } /** * Finds a node with the given name. - * - * @param aName - * Node name. + * + * @param aName Node name. + * * @return Node or null if not found. */ public Node findNode(String aName) { @@ -67,33 +74,35 @@ public class Graph { return node; } } + return null; } /** * Removes a node. - * - * @param aNode - * Node to remove. + * + * @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. + * + * @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"); + + 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. - * + * + * @param aNodes Nodes to add. + * * @see #addNode(Node) */ public void addNodes(List aNodes) { @@ -104,42 +113,47 @@ public class Graph { /** * 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. + * + * @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"); + + "' already exists"); } + if (!nodes.contains(aEdge.getFrom())) { throw new IllegalArgumentException("From node '" + aEdge.getFrom() - + "' from edge '" + aEdge + "' is not part of the graph"); + + "' 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"); + + "' 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. + * 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. + * Adds a number of edges. + * + * @param aEdges Edges to add. */ public void addEdges(List aEdges) { for (Edge edge : aEdges) { @@ -148,25 +162,29 @@ public class Graph { } /** - * Gets the nodes. - * @return Copy of the list of nodes of the graph. + * Gets the nodes. + * + * @return Copy of the list of nodes of the graph. */ public List getNodes() { return new ArrayList(nodes); } /** - * Gets the edges. - * @return Copy of the list of edges of the graph. + * Gets the edges. + * + * @return Copy of the list of edges of the graph. */ public List getEdges() { return new ArrayList(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. + * 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) { @@ -175,67 +193,79 @@ public class Graph { } } } - + /** - * Applies a filter to the graph for removing elements. - * @param aFilter Filter to apply. + * Applies a filter to the graph for removing elements. + * + * @param aFilter Filter to apply. */ public void applyFilter(EdgeFilter aFilter) { - for (Iterator edge = edges.iterator(); edge.hasNext(); ) { - if (aFilter.isViolated(edge.next())) { + for (Iterator edge = edges.iterator(); edge.hasNext();) { + if (aFilter.isViolated(edge.next())) { edge.remove(); } } } /** - * Finds all outgoing edges of a node. More specifically, finds - * all edges e for which e.getFrom().getName() = aNode.getName(). - * @param aNode Node for which to find outgoing edges. - * @return List of outgoing edges. + * Finds all outgoing edges of a node. More specifically, finds + * all edges e for which e.getFrom().getName() = + * aNode.getName(). + * + * @param aNode Node for which to find outgoing edges. + * + * @return List of outgoing edges. */ public List findOutgoing(Node aNode) { List result = new ArrayList(); + 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 e for which e.getTo().getName() = aNode.getName(). - * @param aNode Node for which to find incoming edges. - * @return List of incoming edges. + * Finds all incoming edges of a node. More specifically, finds + * all edges e for which e.getTo().getName() = + * aNode.getName(). + * + * @param aNode Node for which to find incoming edges. + * + * @return List of incoming edges. */ public List findIncoming(Node aNode) { List result = new ArrayList(); + 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. + * 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 nodes = getNodes(); // copy to make sure the visitor can - // modify the - // list of nodes as part of the loop. + // modify the + // list of nodes as part of the loop. + List edges = getEdges(); // copy ..... (see above). for (Node node : nodes) { aVisitor.visitNode(node); } + for (Edge edge : edges) { aVisitor.visitEdge(edge); } diff --git a/system/general/src/main/java/org/wamblee/system/graph/Node.java b/system/general/src/main/java/org/wamblee/system/graph/Node.java index d1df3c03..bf7f4770 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/Node.java +++ b/system/general/src/main/java/org/wamblee/system/graph/Node.java @@ -1,18 +1,18 @@ /* * 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; /** @@ -20,11 +20,10 @@ package org.wamblee.system.graph; * @author Erik Brakkee */ public interface Node { - /** - * Gets the node name uniquely identifying the node in the graph. - * @return Node name. + * Gets the node name uniquely identifying the node in the graph. + * + * @return Node name. */ String getName(); - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/Visitor.java b/system/general/src/main/java/org/wamblee/system/graph/Visitor.java index e65a535c..2f3bdb5a 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/Visitor.java +++ b/system/general/src/main/java/org/wamblee/system/graph/Visitor.java @@ -1,18 +1,18 @@ /* * 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; /** @@ -21,16 +21,17 @@ package org.wamblee.system.graph; * */ public interface Visitor { - /** * Visits a node. Called by {@link Graph#accept(Visitor)}. - * @param aNode Node to visit. + * + * @param aNode Node to visit. */ - void visitNode(Node aNode); - + void visitNode(Node aNode); + /** * Visits a node. Called by {@link Graph#accept(Visitor)}. - * @param aEdge Edge to visit. + * + * @param aEdge Edge to visit. */ - void visitEdge(Edge aEdge); + void visitEdge(Edge aEdge); } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java b/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java index b63a03b5..457ae1d8 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java @@ -1,74 +1,99 @@ /* * 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; +import java.util.List; + + /** - * Visitor that checks whether all externally provided interfaces are actually provided - * by any of the internal components. - * - * @author Erik Brakkee + * 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; - /** + * DOCUMENT ME! + */ + private Graph graph; + +/** * Constructs the visitor. * @param aGraph Component graph. */ - public CheckExternallyProvidedVisitor(Graph aGraph) { - graph = aGraph; + public CheckExternallyProvidedVisitor(Graph aGraph) { + graph = aGraph; } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + */ @Override public void visitEdge(Edge aEdge) { // Empty. } + /** + * DOCUMENT ME! + * + * @param aNode DOCUMENT ME! + */ @Override public void visitNode(Node aNode) { - if ( aNode instanceof ExternalProvidedInterfaceNode) { - ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode; - List edges = graph.findOutgoing(provided); - if ( edges.size() > 2 ) { - createDuplicateException("External provided interfaces has multiple internal matches", aNode, edges); + if (aNode instanceof ExternalProvidedInterfaceNode) { + ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode; + List 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"); + + 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 edges) { + + /** + * DOCUMENT ME! + * + * @param aMsg DOCUMENT ME! + * @param aNode DOCUMENT ME! + * @param edges DOCUMENT ME! + */ + private void createDuplicateException(String aMsg, Node aNode, + List edges) { StringBuffer buf = new StringBuffer(); - buf.append(aNode - + ": " + aMsg + ": "); + buf.append(aNode + ": " + aMsg + ": "); + for (Edge edge : edges) { buf.append(edge.getTo() + "/ "); } + throw new SystemAssemblyException(buf.toString()); } - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java b/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java index 4ab72426..63eadfbe 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,46 +15,68 @@ */ 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; +import java.util.List; + + /** - * Visitor that checks whether all required external interfaces of the container - * are provided. - * + * Visitor that checks whether all required external interfaces of the + * container are provided. + * * @author Erik Brakkee - * */ public class CheckExternallyRequiredVisitor implements Visitor { - + /** + * DOCUMENT ME! + */ private Log LOG = LogFactory.getLog(CheckExternallyRequiredVisitor.class); + /** + * DOCUMENT ME! + */ private Graph graph; + /** + * Creates a new CheckExternallyRequiredVisitor object. + * + * @param aGraph DOCUMENT ME! + */ public CheckExternallyRequiredVisitor(Graph aGraph) { graph = aGraph; } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + */ @Override public void visitEdge(Edge aEdge) { // Empty. } + /** + * DOCUMENT ME! + * + * @param aNode DOCUMENT ME! + */ @Override public void visitNode(Node aNode) { if (aNode instanceof ExternalRequiredInterfaceNode) { ExternalRequiredInterfaceNode required = (ExternalRequiredInterfaceNode) aNode; + if (!required.getRequired().isOptional() - && required.getRequired().getProvider() == null) { + && (required.getRequired().getProvider() == null)) { throw new SystemAssemblyException(aNode - + ": External required interface is not provided"); + + ": External required interface is not provided"); } List edges = graph.findIncoming(aNode); @@ -62,19 +84,20 @@ public class CheckExternallyRequiredVisitor implements Visitor { 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; + + 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); + throw new SystemAssemblyException(aNode + + ": externally required interface is optional but a corresponding internal required interface is mandatory: " + + reqNode); } } } } - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java b/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java index 58cd2cf5..86c13ca3 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,72 +15,103 @@ */ 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; +import java.util.List; + + /** * Visitor that checks whether required and provided interfaces are matched * appropriately: - *
    - *
  • Each required interface is connected to at most one provided interface - *
  • - *
  • Required interfaces that are not optional must be connected to precisely - * one provided interface
  • - *
- * + *
    + *
  • Each required interface is connected to at most one + * provided interface
  • + *
  • Required interfaces that are not optional must be connected + * to precisely one provided interface
  • + *
+ * * @author Erik Brakkee - * */ public class CheckRequiredProvidedMultiplicityVisitor implements Visitor { - + /** + * DOCUMENT ME! + */ private Graph graph; + /** + * Creates a new CheckRequiredProvidedMultiplicityVisitor object. + * + * @param aGraph DOCUMENT ME! + */ public CheckRequiredProvidedMultiplicityVisitor(Graph aGraph) { graph = aGraph; } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + */ @Override public void visitEdge(Edge aEdge) { // Empty } + /** + * DOCUMENT ME! + * + * @param aNode DOCUMENT ME! + */ @Override public void visitNode(Node aNode) { if (aNode instanceof RequiredInterfaceNode) { RequiredInterfaceNode required = (RequiredInterfaceNode) aNode; - List edges = graph.findOutgoing(aNode); + List edges = graph.findOutgoing(aNode); + if (edges.size() > 1) { - createDuplicateException("Multiple providers of required interface found", aNode, edges); + 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"); + + 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 edges = graph.findOutgoing(aNode); - if ( edges.size() > 1) { - createDuplicateException("multiple internal matches for externally provided interface", aNode, edges); + } else if (aNode instanceof ExternalProvidedInterfaceNode) { + List 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"); + + if (edges.size() == 0) { + throw new SystemAssemblyException(aNode + + ": external provided interface is not provided internally"); } } } - private void createDuplicateException(String aMsg, Node aNode, List edges) { + /** + * DOCUMENT ME! + * + * @param aMsg DOCUMENT ME! + * @param aNode DOCUMENT ME! + * @param edges DOCUMENT ME! + */ + private void createDuplicateException(String aMsg, Node aNode, + List edges) { StringBuffer buf = new StringBuffer(); - buf.append(aNode - + ": " + aMsg + ": "); + buf.append(aNode + ": " + aMsg + ": "); + for (Edge edge : edges) { buf.append(edge.getTo() + "/ "); } + throw new SystemAssemblyException(buf.toString()); } - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java b/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java index d18db799..3321bf92 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java @@ -1,67 +1,85 @@ /* * 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; +import java.util.ArrayList; +import java.util.List; + + /** * Checks whether the given component graph can be started in component - * order without any missing dependencies. - * @author Erik Brakkee + * order without any missing dependencies. * + * @author Erik Brakkee */ public class CheckStartupDependenciesVisitor implements Visitor { - - private Graph graph; - private List available; + /** + * DOCUMENT ME! + */ + private Graph graph; /** + * DOCUMENT ME! + */ + private List available; + +/** * Constructs the visitor. * @param aGraph Graph. */ - public CheckStartupDependenciesVisitor(Graph aGraph) { - graph = aGraph; - available = new ArrayList(); + public CheckStartupDependenciesVisitor(Graph aGraph) { + graph = aGraph; + available = new ArrayList(); } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + */ @Override public void visitEdge(Edge aEdge) { // Empty } + /** + * DOCUMENT ME! + * + * @param aNode DOCUMENT ME! + */ @Override public void visitNode(Node aNode) { List edges = graph.findOutgoing(aNode); - + // check dependencies. - for (Edge edge: edges) { + for (Edge edge : edges) { Node dep = edge.getTo(); - if ( !available.contains(dep)) { - throw new SystemAssemblyException(aNode + ": required dependency '" + dep + "' was not started"); + + if (!available.contains(dep)) { + throw new SystemAssemblyException(aNode + + ": required dependency '" + dep + "' was not started"); } } - + available.add(aNode); } - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java b/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java index f772299b..5c77217f 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java @@ -1,24 +1,22 @@ /* * 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; @@ -28,127 +26,151 @@ import org.wamblee.system.graph.Edge; import org.wamblee.system.graph.Graph; import org.wamblee.system.graph.Node; +import java.util.ArrayList; +import java.util.List; + + /** - * 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. + * 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; + /** + * DOCUMENT ME! + */ + private boolean isLinked; /** + * DOCUMENT ME! + */ + private CompositeEdgeFilter edgeFilter; + +/** * Constructs an empty component graph. */ public ComponentGraph() { - isLinked = false; - edgeFilter = new CompositeEdgeFilter(); + 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. + * 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) { + 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. + * 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) { + public void addProvidedInterface(Component aComponent, + ProvidedInterface aInterface) { addNode(new ExternalProvidedInterfaceNode(aComponent, aInterface)); } - + /** - * Validates the component graph. + * Validates the component graph. */ - public void validate() { + public void validate() { extend(new RequiredProvidedEdgeFactory()); applyFilter(edgeFilter); accept(new CheckRequiredProvidedMultiplicityVisitor(this)); - accept(new CheckExternallyRequiredVisitor(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. + * model based on the graph model. */ public void link() { - if ( isLinked ) { - return; + if (isLinked) { + return; } + accept(new LinkVisitor()); - isLinked = true; + isLinked = true; } - + /** - * Finds a list of mappings of external provided interface to internal provided interface. - * - * @return List of pairs of external to internal interface. + * Finds a list of mappings of external provided interface to + * internal provided interface. + * + * @return List of pairs of external to internal interface. */ - public List> findExternalProvidedInterfaceMapping() { - List> result = - new ArrayList>(); - for (Edge edge: getEdges()) { - if ( edge.getFrom() instanceof ExternalProvidedInterfaceNode && - edge.getTo() instanceof ProvidedInterfaceNode ) { - result.add(new Pair( - ((ExternalProvidedInterfaceNode)edge.getFrom()).getProvided(), - ((ProvidedInterfaceNode)edge.getTo()).getProvided() - )); + public List> findExternalProvidedInterfaceMapping() { + List> result = new ArrayList>(); + + for (Edge edge : getEdges()) { + if (edge.getFrom() instanceof ExternalProvidedInterfaceNode + && edge.getTo() instanceof ProvidedInterfaceNode) { + result.add(new Pair( + ((ExternalProvidedInterfaceNode) edge.getFrom()) + .getProvided(), + ((ProvidedInterfaceNode) edge.getTo()).getProvided())); } } - return result; + + return result; } - + /** * Adds a component by adding required interfaces, components, and - * provided interfaces. - * @param aComponent Component to add. + * provided interfaces. + * + * @param aComponent Component to add. */ - public void addComponent(Component aComponent) { + public void addComponent(Component aComponent) { // Add required interfaces. - Node compNode = new ComponentNode(aComponent); + Node compNode = new ComponentNode(aComponent); List requiredNodes = new ArrayList(); - for (RequiredInterface required: aComponent.getRequiredInterfaces()) { - Node reqNode = new RequiredInterfaceNode(aComponent, required); + + 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) { + for (Node reqNode : requiredNodes) { addEdge(new DefaultEdge(compNode, reqNode)); } - + // Add provided interfaces List providedNodes = new ArrayList(); - for (ProvidedInterface provided: aComponent.getProvidedInterfaces()) { - Node provNode = new ProvidedInterfaceNode(aComponent, provided); + + 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) { + for (Node provNode : providedNodes) { addEdge(new DefaultEdge(provNode, compNode)); } } + /** + * DOCUMENT ME! + * + * @param aEdgeFilter DOCUMENT ME! + */ public void addEdgeFilter(CompositeEdgeFilter aEdgeFilter) { - edgeFilter.add(aEdgeFilter); + edgeFilter.add(aEdgeFilter); } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java b/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java index 2ba12614..f07f733f 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java @@ -1,41 +1,59 @@ /* * 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. + * Represents a component node. * + * @author Erik Brakkee. */ public class ComponentNode implements Node { - - private Component component; - - public ComponentNode(Component aComponent) { - component = aComponent; + /** + * DOCUMENT ME! + */ + private Component component; + + /** + * Creates a new ComponentNode object. + * + * @param aComponent DOCUMENT ME! + */ + public ComponentNode(Component aComponent) { + component = aComponent; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String getName() { return component.getQualifiedName(); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Component getComponent() { return component; } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java b/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java index 578bc72f..01c316a0 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,54 +18,95 @@ 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. - * + * Filter used to explicitly connect required and provided interfaces + * within a container. + * * @author Erik Brakkee - * */ public class ConnectExternalProvidedProvidedFilter implements EdgeFilter { - + /** + * DOCUMENT ME! + */ private String externalProvided; + + /** + * DOCUMENT ME! + */ private String component; + + /** + * DOCUMENT ME! + */ 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."); + /** + * Creates a new ConnectExternalProvidedProvidedFilter object. + * + * @param aExternalProvided DOCUMENT ME! + * @param aComponent DOCUMENT ME! + * @param aProvided DOCUMENT ME! + */ + 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 (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"); + + if (provided == null) { + throw new IllegalArgumentException( + "Provided interface name of internal component must be specified"); } } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean isViolated(Edge aEdge) { if (aEdge.getFrom() instanceof ExternalProvidedInterfaceNode && aEdge.getTo() instanceof ProvidedInterfaceNode) { return isViolated((ExternalProvidedInterfaceNode) aEdge.getFrom(), - (ProvidedInterfaceNode) aEdge.getTo()); + (ProvidedInterfaceNode) aEdge.getTo()); } + return false; } + /** + * DOCUMENT ME! + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private boolean isViolated(ExternalProvidedInterfaceNode aFrom, - ProvidedInterfaceNode aTo) { - if ( !aFrom.getName().equals(externalProvided)) { + ProvidedInterfaceNode aTo) { + if (!aFrom.getName().equals(externalProvided)) { return false; // wrong provided interface. } - if ( aTo.getComponent().getName().equals(component) && - aTo.getProvided().getName().equals(provided) ) { + + if (aTo.getComponent().getName().equals(component) + && aTo.getProvided().getName().equals(provided)) { return false; // ok } - return true; + + return true; } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java b/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java index 4c5404b9..b59618d8 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,57 +18,99 @@ 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. - * + * Filter used to explicitly connect required and provided interfaces + * within a container. + * * @author Erik Brakkee - * */ public class ConnectRequiredExternallyRequiredEdgeFilter implements EdgeFilter { - + /** + * DOCUMENT ME! + */ private String client; + + /** + * DOCUMENT ME! + */ private String required; + + /** + * DOCUMENT ME! + */ 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"); + /** + * Creates a new ConnectRequiredExternallyRequiredEdgeFilter object. + * + * @param aClient DOCUMENT ME! + * @param aRequired DOCUMENT ME! + * @param aExternalRequired DOCUMENT ME! + */ + 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 (required == null) { + throw new IllegalArgumentException( + "Required interface must be specified"); } - if ( externalRequired == null ) { - throw new IllegalArgumentException("External required interface must be specified"); + + if (externalRequired == null) { + throw new IllegalArgumentException( + "External required interface must be specified"); } } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean isViolated(Edge aEdge) { if (aEdge.getFrom() instanceof RequiredInterfaceNode && aEdge.getTo() instanceof ExternalRequiredInterfaceNode) { return isViolated((RequiredInterfaceNode) aEdge.getFrom(), - (ExternalRequiredInterfaceNode) aEdge.getTo()); + (ExternalRequiredInterfaceNode) aEdge.getTo()); } + return false; } + /** + * DOCUMENT ME! + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private boolean isViolated(RequiredInterfaceNode aFrom, - ExternalRequiredInterfaceNode aTo) { - if ( !aFrom.getComponent().getName().equals(client)) { + ExternalRequiredInterfaceNode aTo) { + if (!aFrom.getComponent().getName().equals(client)) { return false; // wrong component. } - if ( !(required == null || aFrom.getRequired().getName().equals(required))) { + + if (!((required == null) + || aFrom.getRequired().getName().equals(required))) { return false; // wrong interface } - if ( !aTo.getRequired().getName().equals(externalRequired)) { + + if (!aTo.getRequired().getName().equals(externalRequired)) { return true; // wrong externally required interface. } - - return false; + + return false; } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java b/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java index a3c3f6d5..bb6b1343 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java @@ -1,12 +1,12 @@ /* * 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. @@ -18,59 +18,99 @@ 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. - * + * Filter used to explicitly connect required and provided interfaces + * within a container. + * * @author Erik Brakkee - * */ public class ConnectRequiredProvidedEdgeFilter implements EdgeFilter { - + /** + * DOCUMENT ME! + */ private String client; + + /** + * DOCUMENT ME! + */ private String required; + + /** + * DOCUMENT ME! + */ private String server; + + /** + * DOCUMENT ME! + */ private String provided; + /** + * Creates a new ConnectRequiredProvidedEdgeFilter object. + * + * @param aClient DOCUMENT ME! + * @param aRequired DOCUMENT ME! + * @param aServer DOCUMENT ME! + * @param aProvided DOCUMENT ME! + */ 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"); + String aServer, String aProvided) { + client = aClient; + required = aRequired; + server = aServer; + provided = aProvided; + + if (client == null) { + throw new IllegalArgumentException( + "Client component must be specified"); } } + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public boolean isViolated(Edge aEdge) { if (aEdge.getFrom() instanceof RequiredInterfaceNode && aEdge.getTo() instanceof ProvidedInterfaceNode) { return isViolated((RequiredInterfaceNode) aEdge.getFrom(), - (ProvidedInterfaceNode) aEdge.getTo()); + (ProvidedInterfaceNode) aEdge.getTo()); } + return false; } + /** + * DOCUMENT ME! + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private boolean isViolated(RequiredInterfaceNode aFrom, - ProvidedInterfaceNode aTo) { + ProvidedInterfaceNode aTo) { if (client.equals(aFrom.getComponent().getName()) - && (required == null || required.equals(aFrom.getRequired() - .getName()))) { + && ((required == null) + || required.equals(aFrom.getRequired().getName()))) { // From part matches. - if ( server == null ) { + if (server == null) { return true; // all connections are eliminated } + if (server.equals(aTo.getComponent().getName()) - && (provided == null || provided.equals(aTo.getProvided() - .getName()))) { + && ((provided == null) + || provided.equals(aTo.getProvided().getName()))) { // to part matches also return false; - } - else { + } else { // From matches and to doesn't so edgefilter is violated. - return true; + return true; } } else { // From part does not match, restriction does not apply. diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java b/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java index d4cef89a..2af413e2 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java @@ -1,54 +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.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 + * Represents an external provided interface of a container. * + * @author Erik Brakkee */ public class ExternalProvidedInterfaceNode implements Node { + /** + * DOCUMENT ME! + */ + private Component component; + + /** + * DOCUMENT ME! + */ + private ProvidedInterface provided; - private Component component; - private ProvidedInterface provided; - - public ExternalProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) { - component = aComponent; - provided = aProvided; + /** + * Creates a new ExternalProvidedInterfaceNode object. + * + * @param aComponent DOCUMENT ME! + * @param aProvided DOCUMENT ME! + */ + public ExternalProvidedInterfaceNode(Component aComponent, + ProvidedInterface aProvided) { + component = aComponent; + provided = aProvided; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String getName() { - return provided.getName(); + return provided.getName(); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Component getComponent() { return component; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public ProvidedInterface getProvided() { return provided; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { - return component.getQualifiedName() + ":" + provided; + return component.getQualifiedName() + ":" + provided; } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java b/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java index 6b71ffea..59fcb403 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java @@ -1,52 +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 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 + * Represents an externally required interface of a container. * + * @author Erik Brakkee */ public class ExternalRequiredInterfaceNode implements Node { - + /** + * DOCUMENT ME! + */ private Component component; - private RequiredInterface required; - public ExternalRequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) { - component = aComponent; - required = aRequired; + /** + * DOCUMENT ME! + */ + private RequiredInterface required; + + /** + * Creates a new ExternalRequiredInterfaceNode object. + * + * @param aComponent DOCUMENT ME! + * @param aRequired DOCUMENT ME! + */ + public ExternalRequiredInterfaceNode(Component aComponent, + RequiredInterface aRequired) { + component = aComponent; + required = aRequired; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String getName() { - return required.getName(); + return required.getName(); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Component getComponent() { return component; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public RequiredInterface getRequired() { return required; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { return component.getQualifiedName() + ":" + required; diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java b/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java index cc2007ff..d06280c9 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java @@ -1,12 +1,12 @@ /* * 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. @@ -22,39 +22,44 @@ 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. - * + * 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 { - + /** + * DOCUMENT ME! + * + * @param aEdge DOCUMENT ME! + */ @Override public void visitEdge(Edge aEdge) { Node from = aEdge.getFrom(); - Node to = aEdge.getTo(); + Node to = aEdge.getTo(); + if (from instanceof RequiredInterfaceNode) { RequiredInterfaceNode required = (RequiredInterfaceNode) from; - if (to instanceof ProvidedInterfaceNode) { + 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()) { + ProvidedInterface provider = external.getRequired() + .getProvider(); + + if ((provider == null) && !required.getRequired().isOptional()) { throw new SystemAssemblyException("Mandatory interface '" - + from + "' is not provided."); + + from + "' is not provided."); } - if ( provider != null ) { + + if (provider != null) { required.getRequired().setProvider(provider); } } @@ -64,9 +69,13 @@ public class LinkVisitor implements Visitor { } } + /** + * DOCUMENT ME! + * + * @param aNode DOCUMENT ME! + */ @Override public void visitNode(Node aNode) { // Empty. } - } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java b/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java index 206bdc9f..7f6d5920 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java @@ -1,53 +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.graph.component; import org.wamblee.system.core.Component; import org.wamblee.system.core.ProvidedInterface; import org.wamblee.system.graph.Node; + /** - * Provided interface node. + * Provided interface node. + * * @author Erik Brakkee */ public class ProvidedInterfaceNode implements Node { - - private Component component; + /** + * DOCUMENT ME! + */ + private Component component; + + /** + * DOCUMENT ME! + */ private ProvidedInterface provided; - - public ProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) { - component = aComponent; - provided = aProvided; + + /** + * Creates a new ProvidedInterfaceNode object. + * + * @param aComponent DOCUMENT ME! + * @param aProvided DOCUMENT ME! + */ + public ProvidedInterfaceNode(Component aComponent, + ProvidedInterface aProvided) { + component = aComponent; + provided = aProvided; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String getName() { - return component.getQualifiedName() + ":" + provided.getName(); + return component.getQualifiedName() + ":" + provided.getName(); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public ProvidedInterface getProvided() { return provided; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Component getComponent() { return component; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { - return component.getQualifiedName() + ":" + provided; + return component.getQualifiedName() + ":" + provided; } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java b/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java index bdf4f89e..9b50eb9c 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java @@ -1,54 +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.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 + * 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; + /** + * DOCUMENT ME! + */ + private Component component; + + /** + * DOCUMENT ME! + */ + private RequiredInterface required; + + /** + * Creates a new RequiredInterfaceNode object. + * + * @param aComponent DOCUMENT ME! + * @param aRequired DOCUMENT ME! + */ + public RequiredInterfaceNode(Component aComponent, + RequiredInterface aRequired) { + component = aComponent; + required = aRequired; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String getName() { return component.getQualifiedName() + ":" + required.getName(); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public RequiredInterface getRequired() { return required; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Component getComponent() { return component; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public String toString() { - return component.getQualifiedName() + ":" + required; + return component.getQualifiedName() + ":" + required; } } diff --git a/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java b/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java index 711501a1..3f89884f 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,60 +15,75 @@ */ 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; +import java.util.ArrayList; +import java.util.List; + + /** * Factory that creates edges between required and provided interfaces. - * Speciflcally it creates: - *
    - *
  • Edges between provided and required interfaces of a container.
  • - *
  • Edges between required and externally required interfaces
  • - *
  • Edges between externally provided and provided interfaces. - *
- * + * Speciflcally it creates: + *
    + *
  • Edges between provided and required interfaces of a + * container.
  • + *
  • Edges between required and externally required interfaces
  • + *
  • Edges between externally provided and provided interfaces. + *
+ * * @author Erik Brakkee - * */ public class RequiredProvidedEdgeFactory implements EdgeFactory { - + /** + * Creates a new RequiredProvidedEdgeFactory object. + */ public RequiredProvidedEdgeFactory() { // Empty. } + /** + * DOCUMENT ME! + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public List create(Node aFrom, Node aTo) { List result = new ArrayList(); + if (aFrom instanceof RequiredInterfaceNode) { RequiredInterfaceNode required = (RequiredInterfaceNode) aFrom; + if (aTo instanceof ProvidedInterfaceNode) { - ProvidedInterfaceNode provided = (ProvidedInterfaceNode) aTo; - if (required.getRequired() - .implementedBy(provided.getProvided())) { + + 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())) { + + 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())) { + } 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/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java b/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java index f886d788..18a03ce0 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java +++ b/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java @@ -28,4 +28,3 @@ 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/system/general/src/main/java/org/wamblee/system/graph/package-info.java b/system/general/src/main/java/org/wamblee/system/graph/package-info.java index 6a2318ec..3756573b 100644 --- a/system/general/src/main/java/org/wamblee/system/graph/package-info.java +++ b/system/general/src/main/java/org/wamblee/system/graph/package-info.java @@ -17,4 +17,5 @@ *
  • {@link EdgeFactory}: For extending the graph with new edges
  • * */ -package org.wamblee.system.graph; \ No newline at end of file +package org.wamblee.system.graph; + diff --git a/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java b/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java index 6dca8fe7..97c8eed8 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java @@ -1,37 +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.system.adapters; +import junit.framework.TestCase; + 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class AdapterTestCase extends TestCase { - - protected Scope scope; - static EventTracker EVENT_TRACKER; + /** + * DOCUMENT ME! + */ + static EventTracker EVENT_TRACKER; - @Override - protected void setUp() throws Exception { - super.setUp(); - EVENT_TRACKER = new EventTracker(); - scope = new DefaultScope(new ProvidedInterface[0]); - } + /** + * DOCUMENT ME! + */ + protected Scope scope; + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + EVENT_TRACKER = new EventTracker(); + scope = new DefaultScope(new ProvidedInterface[0]); + } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java b/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java index 5e4f868f..6a48e045 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java @@ -1,18 +1,18 @@ /* * 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; @@ -20,72 +20,91 @@ 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 { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ClassAdapterTest extends AdapterTestCase { + /** + * DOCUMENT ME! + */ + public void testSimpleConstructorInjection() { + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); - 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(); + + 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()); - + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + Object obj1 = scope.getRuntime(x1Adapter); - assertTrue(obj1 instanceof X1); + 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(); + } + + /** + * DOCUMENT ME! + */ + 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()); - + + 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); + 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; - + + 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/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java b/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java index da5ff6f8..5baaad55 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,26 +15,36 @@ */ 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 { +import java.util.Collections; +import java.util.List; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ClassConfigurationTest extends AdapterTestCase { + /** + * DOCUMENT ME! + */ public void testConstructorConfig() { - ClassConfiguration classConfig = new ClassConfiguration(X1.class); + ClassConfiguration classConfig = new ClassConfiguration(X1.class); + + ConstructorConfiguration config = classConfig.getConstructorConfig() + .greedy(); - ConstructorConfiguration config = classConfig.getConstructorConfig() - .greedy(); - - ProvidedInterface provided = new DefaultProvidedInterface("arg", + ProvidedInterface provided = new DefaultProvidedInterface("arg", String.class); - List required = classConfig.getRequiredInterfaces(); + List required = classConfig.getRequiredInterfaces(); assertEquals(1, required.size()); assertFalse(required.get(0).isOptional()); @@ -45,20 +55,26 @@ public class ClassConfigurationTest extends AdapterTestCase { classConfig.create(scope); AssertionUtils.assertEquals(new String[] { "x1(hello)" }, - AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread()) - .toArray()); + AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread()) + .toArray()); } + /** + * DOCUMENT ME! + */ 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", + classConfig.getObjectConfig().getSetterConfig().initAllSetters() + .values("setPort").setValue(0, 10); + + ProvidedInterface providedBoolean = new DefaultProvidedInterface("boolean", Boolean.class); - ProvidedInterface providedHost = new DefaultProvidedInterface("host", String.class); - List required = classConfig.getRequiredInterfaces(); + ProvidedInterface providedHost = new DefaultProvidedInterface("host", + String.class); + List required = classConfig + .getRequiredInterfaces(); Collections.sort(required, new RequiredInterfaceComparator()); assertEquals(2, required.size()); @@ -69,19 +85,19 @@ public class ClassConfigurationTest extends AdapterTestCase { scope.publishInterface(providedBoolean, true); scope.publishInterface(providedHost, "host.name.org"); - + Object obj = classConfig.create(scope); assertTrue(obj instanceof X7); - X7 x7 = (X7)obj; + + 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/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java b/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java index fe0ece62..cf049173 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,127 +15,166 @@ */ 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 { +import java.util.List; + - public void testGreedyUnique() { - ConstructorConfiguration config = new ConstructorConfiguration(X1.class) - .greedy(); - ProvidedInterface provided = new DefaultProvidedInterface("arg", - String.class); - List 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 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 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 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 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()); - } +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ConstructorConfigurationTest extends AdapterTestCase { + /** + * DOCUMENT ME! + */ + public void testGreedyUnique() { + ConstructorConfiguration config = new ConstructorConfiguration(X1.class) + .greedy(); + ProvidedInterface provided = new DefaultProvidedInterface("arg", + String.class); + List 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()); + } + + /** + * DOCUMENT ME! + */ + public void testGreedyNonUnique() { + try { + ConstructorConfiguration config = new ConstructorConfiguration(X2.class) + .greedy(); + } catch (SystemAssemblyException e) { + // e.printStackTrace(); + return; + } + + fail(); + } + + /** + * DOCUMENT ME! + */ + public void testSpecificConstructor() { + ConstructorConfiguration config = new ConstructorConfiguration(X2.class) + .select(String.class); + ProvidedInterface provided = new DefaultProvidedInterface("arg", + String.class); + List 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()); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + public void testOptionalValueProvided() { + ConstructorConfiguration config = new ConstructorConfiguration(X1.class) + .greedy(); + config.getParameters().setOptional(0); + + ProvidedInterface provided = new DefaultProvidedInterface("arg", + String.class); + List 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()); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + public void testIgnoredNonPublic() { + ConstructorConfiguration config = new ConstructorConfiguration(X3.class) + .greedy(); + List required = config.getRequiredInterfaces(); + assertEquals(0, config.getParameters().getTypes().length); + } + + /** + * DOCUMENT ME! + */ + public void testNonPublicConstructor() { + ConstructorConfiguration config = new ConstructorConfiguration(X3.class).setNonPublic(true) + .greedy(); + ProvidedInterface provided = new DefaultProvidedInterface("arg", + String.class); + List 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/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java b/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java index 938a1222..108cd961 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -16,69 +16,89 @@ package org.wamblee.system.adapters; import org.wamblee.system.core.Scope; + import org.wamblee.test.AssertionUtils; -public class DefaultContainerTest extends AdapterTestCase { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class DefaultContainerTest extends AdapterTestCase { + /** + * DOCUMENT ME! + */ 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); + DefaultContainer container = new DefaultContainer("top").addComponent("x1", + x1Config).addComponent("x4", x4Config); - Scope scope = container.start(); + Scope scope = container.start(); AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" }, - EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); Object obj = scope.getRuntime("x1"); assertTrue(obj instanceof X1); obj = scope.getRuntime("x4"); assertTrue(obj instanceof X4); } - + + /** + * DOCUMENT ME! + */ public void testConstructorInjectionAndSetterInjection() { ClassConfiguration x1Config = new ClassConfiguration(X1.class); x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); x1Config.getObjectConfig().getSetterConfig().initAllSetters(); - - X8 x8 = new X8(null); + + 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()); + 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() { + + /** + * DOCUMENT ME! + */ + 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); + @Override + public void run() throws Exception { + container.addComponent("x", "y", + new ObjectConfiguration(Integer.class)); + } + }, IllegalArgumentException.class); } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java b/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java index 0c6825e7..ef9f0a9c 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java @@ -1,23 +1,20 @@ /* * 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; @@ -25,48 +22,64 @@ 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; +import java.util.Collections; +import java.util.List; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class ObjectAdapterTest extends AdapterTestCase { + /** + * DOCUMENT ME! + */ + public void testSetterInjection() { + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); - 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); + + 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]); - + + 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()); - + 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); + 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/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java b/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java index ce0a8d89..8f27f3ed 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,7 +15,15 @@ */ package org.wamblee.system.adapters; +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; + import java.lang.reflect.Method; + import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -23,304 +31,363 @@ 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class SetterConfigurationTest extends AdapterTestCase { + /** + * DOCUMENT ME! + */ + public void testOneSetter() { + SetterConfiguration config = new SetterConfiguration(X5.class); + config.initAllSetters(); + + List 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()); + } + + /** + * DOCUMENT ME! + */ + public void testPrivateSetter() { + SetterConfiguration config = new SetterConfiguration(X5.class); + config.setNonPublic(true); + config.initAllSetters(); + + List required = new ArrayList(config + .getRequiredInterfaces()); + Collections.sort(required, + new Comparator() { + @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()); + } + + /** + * DOCUMENT ME! + */ + public void testInheritance() { + SetterConfiguration config = new SetterConfiguration(X9.class); + config.setNonPublic(true); + config.initAllSetters(); + + List required = new ArrayList(config + .getRequiredInterfaces()); + Collections.sort(required, + new Comparator() { + @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()); + } + + /** + * DOCUMENT ME! + */ + public void testMultipleSetters() { + SetterConfiguration config = new SetterConfiguration(X6.class) + .initAllSetters(); + List 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()); + } + + /** + * DOCUMENT ME! + */ + public void testInvokeWrongType() { + final SetterConfiguration config = new SetterConfiguration(X5.class) + .initAllSetters(); + List 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); + } + + /** + * DOCUMENT ME! + */ + public void testSetExplicitValue() { + SetterConfiguration config = new SetterConfiguration(X5.class) + .initAllSetters(); + config.values("setValue").setValue(0, "bladibla"); + + List required = config.getRequiredInterfaces(); + assertEquals(0, required.size()); + + X5 obj = new X5(); + assertNull(obj.getValue()); + config.inject(scope, obj); + assertEquals("bladibla", obj.getValue()); + } + + /** + * DOCUMENT ME! + */ + public void testClear() { + SetterConfiguration config = new SetterConfiguration(X6.class); + config.clear(); + + List 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 testOneSetter() { - SetterConfiguration config = new SetterConfiguration(X5.class); - config.initAllSetters(); - List 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 required = new ArrayList( - config.getRequiredInterfaces()); - Collections.sort(required, new Comparator() { - @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 required = new ArrayList( - config.getRequiredInterfaces()); - Collections.sort(required, new Comparator() { - @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 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 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 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 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 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 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 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(); + /** + * DOCUMENT ME! + */ + public void testAddByName() { + SetterConfiguration config = new SetterConfiguration(X6.class); + config.clear().add("setHost"); + + List 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()); + } + + /** + * DOCUMENT ME! + */ + public void testAddByType() { + SetterConfiguration config = new SetterConfiguration(X6.class); + config.clear().addSetter(String.class); + + List 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()); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + public void testRemove() { + SetterConfiguration config = new SetterConfiguration(X6.class) + .initAllSetters(); + config.remove("setPort"); + + List 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()); + } + + /** + * DOCUMENT ME! + * + * @throws NoSuchMethodException DOCUMENT ME! + */ + public void testRemoveByMethodObject() throws NoSuchMethodException { + SetterConfiguration config = new SetterConfiguration(X6.class) + .initAllSetters(); config.remove(X6.class.getMethod("setPort", Integer.class)); + List required = config.getRequiredInterfaces(); Collections.sort(required, new RequiredInterfaceComparator()); assertEquals(1, required.size()); @@ -340,25 +407,33 @@ public class SetterConfigurationTest extends AdapterTestCase { 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 methods = config.getSetters(); - assertEquals(2, methods.size()); - for (Method method: methods) { - assertEquals(X10.class, method.getDeclaringClass()); - } - - } + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + public void testOverridingSetters() { + SetterConfiguration config = new SetterConfiguration(X10.class) + .initAllSetters(); + assertEquals(2, config.getRequiredInterfaces().size()); + + List methods = config.getSetters(); + assertEquals(2, methods.size()); + + for (Method method : methods) { + assertEquals(X10.class, method.getDeclaringClass()); + } + } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X1.java b/system/general/src/test/java/org/wamblee/system/adapters/X1.java index b17a27c0..c41b43ad 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X1.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X1.java @@ -1,26 +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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X1 { - public X1() { - AdapterTestCase.EVENT_TRACKER.eventOccurred("x1()"); - } + /** + * Creates a new X1 object. + */ + public X1() { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x1()"); + } - public X1(String aValue) { - AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")"); - } -} \ No newline at end of file + /** + * Creates a new X1 object. + * + * @param aValue DOCUMENT ME! + */ + public X1(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")"); + } +} diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X10.java b/system/general/src/test/java/org/wamblee/system/adapters/X10.java index fc8b90a5..3f3f47ac 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X10.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X10.java @@ -1,26 +1,53 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.system.adapters; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X10 extends X6 { + /** + * DOCUMENT ME! + * + * @param aHost DOCUMENT ME! + */ + @Override + public void setHost(String aHost) { + super.setHost(aHost); + } - - @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); - } - + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getHost() { + return super.getHost(); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Integer getPort() { + return super.getPort(); + } + + /** + * DOCUMENT ME! + * + * @param aPort DOCUMENT ME! + */ + @Override + public void setPort(Integer aPort) { + super.setPort(aPort); + } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X11.java b/system/general/src/test/java/org/wamblee/system/adapters/X11.java index 4ddc11eb..86b0f71a 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X11.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X11.java @@ -1,14 +1,29 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.system.adapters; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X11 { - - - public void setX(String aValue) { - - } - - public void setY(String aValue) { - - } + /** + * DOCUMENT ME! + * + * @param aValue DOCUMENT ME! + */ + public void setX(String aValue) { + } + /** + * DOCUMENT ME! + * + * @param aValue DOCUMENT ME! + */ + public void setY(String aValue) { + } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X2.java b/system/general/src/test/java/org/wamblee/system/adapters/X2.java index 50a59027..62fc932d 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X2.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X2.java @@ -1,26 +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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X2 { - public X2(Integer aInteger) { - AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aInteger + ")"); - } + /** + * Creates a new X2 object. + * + * @param aInteger DOCUMENT ME! + */ + 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 + /** + * Creates a new X2 object. + * + * @param aValue DOCUMENT ME! + */ + public X2(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aValue + ")"); + } +} diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X3.java b/system/general/src/test/java/org/wamblee/system/adapters/X3.java index 4601a033..1f8f9255 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X3.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X3.java @@ -1,26 +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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X3 { - public X3() { - AdapterTestCase.EVENT_TRACKER.eventOccurred("x3()"); - } + /** + * Creates a new X3 object. + */ + public X3() { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x3()"); + } - protected X3(String aValue) { - AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")"); - } -} \ No newline at end of file + /** + * Creates a new X3 object. + * + * @param aValue DOCUMENT ME! + */ + protected X3(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")"); + } +} diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X4.java b/system/general/src/test/java/org/wamblee/system/adapters/X4.java index 8471ca97..a8a343ca 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X4.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X4.java @@ -1,30 +1,48 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X4 { + /** + * DOCUMENT ME! + */ + private X1 x1; - private X1 x1; - - public X4(X1 aX1) { - AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)"); - x1 = aX1; - } - - public X1 getX1() { - return x1; - } + /** + * Creates a new X4 object. + * + * @param aX1 DOCUMENT ME! + */ + public X4(X1 aX1) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)"); + x1 = aX1; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public X1 getX1() { + return x1; + } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X5.java b/system/general/src/test/java/org/wamblee/system/adapters/X5.java index c411b59e..78fd8e3f 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X5.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X5.java @@ -1,47 +1,85 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ 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() { + /** + * DOCUMENT ME! + */ + private String value; + + /** + * DOCUMENT ME! + */ + private Integer xyz; + + /** + * Creates a new X5 object. + */ + public X5() { + } + + /** + * DOCUMENT ME! + * + * @param aValue DOCUMENT ME! + */ + public void setValue(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue + + ")"); + value = aValue; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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 + + /** + * DOCUMENT ME! + */ + public void doSomething() { + // Empty. + } + + /** + * DOCUMENT ME! + * + * @param aXyz DOCUMENT ME! + */ + private void setXyz(int aXyz) { + xyz = aXyz; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Integer getXyz() { + return xyz; + } +} diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X6.java b/system/general/src/test/java/org/wamblee/system/adapters/X6.java index 9535b358..c76c8d7c 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X6.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X6.java @@ -1,42 +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.adapters; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X6 { - - private String host; - private Integer port; - - public X6() { - - } + /** + * DOCUMENT ME! + */ + private String host; - public Integer getPort() { + /** + * DOCUMENT ME! + */ + private Integer port; + + /** + * Creates a new X6 object. + */ + public X6() { + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Integer getPort() { return port; } - - public void setPort(Integer aPort) { + + /** + * DOCUMENT ME! + * + * @param aPort DOCUMENT ME! + */ + public void setPort(Integer aPort) { port = aPort; } - - public String getHost() { + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getHost() { return host; } - - public void setHost(String aHost) { + + /** + * DOCUMENT ME! + * + * @param aHost DOCUMENT ME! + */ + public void setHost(String aHost) { host = aHost; } -} \ No newline at end of file +} diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X7.java b/system/general/src/test/java/org/wamblee/system/adapters/X7.java index 390011d4..e238b3b0 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X7.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X7.java @@ -1,47 +1,93 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X7 { - - private String host; + /** + * DOCUMENT ME! + */ + private String host; + + /** + * DOCUMENT ME! + */ private Integer port; - private Boolean flag; - - public X7(Boolean aBoolean) { - flag = aBoolean; - } - - public Boolean getBoolean() { + + /** + * DOCUMENT ME! + */ + private Boolean flag; + + /** + * Creates a new X7 object. + * + * @param aBoolean DOCUMENT ME! + */ + public X7(Boolean aBoolean) { + flag = aBoolean; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Boolean getBoolean() { return flag; } - public Integer getPort() { + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Integer getPort() { return port; } - - public void setPort(Integer aPort) { + + /** + * DOCUMENT ME! + * + * @param aPort DOCUMENT ME! + */ + public void setPort(Integer aPort) { port = aPort; } - - public String getHost() { + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getHost() { return host; } - - public void setHost(String aHost) { + + /** + * DOCUMENT ME! + * + * @param aHost DOCUMENT ME! + */ + public void setHost(String aHost) { host = aHost; } -} \ No newline at end of file +} diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X8.java b/system/general/src/test/java/org/wamblee/system/adapters/X8.java index ebfedc37..ec083b14 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X8.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X8.java @@ -1,40 +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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X8 { + /** + * DOCUMENT ME! + */ + private X1 x1; - 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)"); + /** + * DOCUMENT ME! + */ + private X4 x4; + + /** + * Creates a new X8 object. + * + * @param aX1 DOCUMENT ME! + */ + public X8(X1 aX1) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)"); + x1 = aX1; + } + + /** + * DOCUMENT ME! + * + * @param aX4 DOCUMENT ME! + */ + public void setX4(X4 aX4) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)"); x4 = aX4; } - - public X4 getX4() { + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public X4 getX4() { return x4; } - - public X1 getX1() { - return x1; - } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public X1 getX1() { + return x1; + } } diff --git a/system/general/src/test/java/org/wamblee/system/adapters/X9.java b/system/general/src/test/java/org/wamblee/system/adapters/X9.java index d11a7cb5..9d1d6ce9 100644 --- a/system/general/src/test/java/org/wamblee/system/adapters/X9.java +++ b/system/general/src/test/java/org/wamblee/system/adapters/X9.java @@ -1,18 +1,42 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.system.adapters; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class X9 extends X5 { - - private boolean flag; - - public X9() { - - } + /** + * DOCUMENT ME! + */ + private boolean flag; - public boolean isFlag() { - return flag; - } - + /** + * Creates a new X9 object. + */ + public X9() { + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public boolean isFlag() { + return flag; + } + + /** + * DOCUMENT ME! + * + * @param aFlag DOCUMENT ME! + */ public void setFlag(boolean aFlag) { - flag = aFlag; - } + flag = aFlag; + } } diff --git a/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java b/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java index 10e67958..e903b9de 100644 --- a/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java +++ b/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java @@ -1,64 +1,99 @@ /* * 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; +import java.util.Properties; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DatabaseComponent extends AbstractComponent { - - private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps", Properties.class); - - private Database database; - - public DatabaseComponent(String aName, Database aDatabase) { - super(aName); + /** + * DOCUMENT ME! + */ + private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps", + Properties.class); + + /** + * DOCUMENT ME! + */ + private Database database; + + /** + * Creates a new DatabaseComponent object. + * + * @param aName DOCUMENT ME! + * @param aDatabase DOCUMENT ME! + */ + public DatabaseComponent(String aName, Database aDatabase) { + super(aName); database = aDatabase; addProvidedInterface(DB_PROPS); } + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected Database doStart(Scope aScope) { - database.start(); - + database.start(); + Properties props = new Properties(); - if ( database instanceof DerbyDatabase ) { + + if (database instanceof DerbyDatabase) { props.put("database.type", DatabaseType.DERBY.toString()); - } else { - throw new IllegalArgumentException("Unknown database type " + database); + } 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; + + return database; } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ @Override protected void doStop(Database aRuntime) { database.stop(); } - } diff --git a/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java b/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java index 4c100fcc..39a8fdaa 100644 --- a/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java +++ b/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java @@ -1,12 +1,12 @@ /* * 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. @@ -16,18 +16,28 @@ package org.wamblee.system.components; import org.wamblee.support.persistence.DatabaseBuilder; + import org.wamblee.system.container.Container; -public class DatabaseComponentFactory { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class DatabaseComponentFactory { + /** + * DOCUMENT ME! + * + * @param aContainer DOCUMENT ME! + */ public static void addDatabaseConfig(Container aContainer) { try { aContainer.addComponent(new DatabaseComponent("db", - DatabaseBuilder.getDatabase())); + DatabaseBuilder.getDatabase())); } catch (Exception e) { - throw new RuntimeException("Could not add database configuration", - e); + throw new RuntimeException("Could not add database configuration", e); } } - } diff --git a/system/general/src/test/java/org/wamblee/system/container/Application.java b/system/general/src/test/java/org/wamblee/system/container/Application.java index e6b09215..9e4a56b4 100644 --- a/system/general/src/test/java/org/wamblee/system/container/Application.java +++ b/system/general/src/test/java/org/wamblee/system/container/Application.java @@ -1,12 +1,12 @@ /* * 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. @@ -20,81 +20,172 @@ 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 { - 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, ""); - } +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class Application extends AbstractComponent { + /** + * DOCUMENT ME! + */ private EventTracker tracker; + + /** + * DOCUMENT ME! + */ private String string; + + /** + * DOCUMENT ME! + */ private Integer integer; + + /** + * DOCUMENT ME! + */ private double random; + /** + * Creates a new Application object. + */ public Application() { this("application"); } + /** + * Creates a new Application object. + * + * @param aName DOCUMENT ME! + */ public Application(String aName) { this(aName, ""); } + /** + * Creates a new Application object. + * + * @param aName DOCUMENT ME! + * @param aPrefix DOCUMENT ME! + */ public Application(String aName, String aPrefix) { - super(aName, new ProvidedInterface[0], required(false, - aPrefix)); + super(aName, new ProvidedInterface[0], required(false, aPrefix)); random = Math.random(); } + /** + * Creates a new Application object. + * + * @param aIsOptinal DOCUMENT ME! + */ public Application(boolean aIsOptinal) { super("application", new ProvidedInterface[0], required(true, "")); } + /** + * Creates a new Application object. + * + * @param aTracker DOCUMENT ME! + */ public Application(EventTracker aTracker) { this(); tracker = aTracker; } + /** + * DOCUMENT ME! + * + * @param aOptional DOCUMENT ME! + * @param aPrefix DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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) + }; + } + + /** + * DOCUMENT ME! + * + * @param aOptional DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public static RequiredInterface[] required(boolean aOptional) { + return required(aOptional, ""); + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public Object doStart(Scope aScope) { track("start." + getName()); - string = aScope.getInterfaceImplementation(getRequiredInterfaces() + string = aScope.getInterfaceImplementation(getRequiredInterfaces() .get(0).getProvider(), String.class); - integer = aScope.getInterfaceImplementation(getRequiredInterfaces() + integer = aScope.getInterfaceImplementation(getRequiredInterfaces() .get(1).getProvider(), Integer.class); + return random; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public String getString() { return string; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public Integer getInteger() { return integer; } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ @Override public void doStop(Object aRuntime) { track("stop." + getName()); + if (random != (Double) aRuntime) { throw new IllegalArgumentException("Wrong runtime: expected " - + random + " but got " + aRuntime); + + random + " but got " + aRuntime); } } + /** + * DOCUMENT ME! + * + * @param aString DOCUMENT ME! + */ private void track(String aString) { if (tracker == null) { return; } + tracker.eventOccurred(aString); } } diff --git a/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java b/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java index bda07b21..1d7d8a54 100644 --- a/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java +++ b/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,13 +15,10 @@ */ 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; @@ -32,714 +29,852 @@ 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 { +import java.io.Serializable; + +import java.util.ArrayList; +import java.util.List; + - private EventTracker tracker; - - @Override - protected void setUp() throws Exception { - super.setUp(); - tracker = new EventTracker(); - } - - private static class MyMultiple implements Serializable, Runnable { - @Override - public void run() { - // Empty - } - } - - private List> createProvidedInput( - ProvidedInterface[] aProvided, Component aProvider) { - List> result = new ArrayList>(); - for (ProvidedInterface provided : aProvided) { - result.add(new Pair(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 required = system.getRequiredInterfaces(); - assertEquals(0, required.size()); - List 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 required = system.getRequiredInterfaces(); - assertEquals(1, required.size()); - List 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 required = system.getRequiredInterfaces(); - assertEquals(2, required.size()); - List 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); - } +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ContainerTest extends TestCase { + /** + * DOCUMENT ME! + */ + private EventTracker tracker; + + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + tracker = new EventTracker(); + } + + /** + * DOCUMENT ME! + * + * @param aProvided DOCUMENT ME! + * @param aProvider DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private List> createProvidedInput( + ProvidedInterface[] aProvided, Component aProvider) { + List> result = new ArrayList>(); + + for (ProvidedInterface provided : aProvided) { + result.add(new Pair(provided, + aProvider)); + } + + return result; + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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 required = system.getRequiredInterfaces(); + assertEquals(0, required.size()); + + List 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])); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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 required = system.getRequiredInterfaces(); + assertEquals(1, required.size()); + + List provided = system.getProvidedInterfaces(); + assertEquals(0, provided.size()); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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 required = system.getRequiredInterfaces(); + assertEquals(2, required.size()); + + List provided = system.getProvidedInterfaces(); + assertEquals(0, provided.size()); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + * @throws RuntimeException DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + * @throws RuntimeException DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + 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(); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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())); + } + + /** + * DOCUMENT ME! + */ + 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())); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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])); + } + + /** + * DOCUMENT ME! + */ + 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()); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + /** + * DOCUMENT ME! + */ + 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())); + } + + /** + * DOCUMENT ME! + */ + 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); + } + + private static class MyMultiple implements Serializable, Runnable { + @Override + public void run() { + // Empty + } + } } diff --git a/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java b/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java index 2fd48f6e..fe73dd99 100644 --- a/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java +++ b/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -17,52 +17,71 @@ package org.wamblee.system.core; import junit.framework.TestCase; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class AbstractComponentTest extends TestCase { + /** + * DOCUMENT ME! + */ + public void testNotAllInterfacesStarted() { + try { + Component component = new AbstractComponent("xx", + new ProvidedInterface[] { + new DefaultProvidedInterface("xxx", String.class) + }, new RequiredInterface[0]) { + @Override + protected Object doStart(Scope aScope) { + // Empty, not starting service. + return null; + } - public void testNotAllInterfacesStarted() { - try { - Component component = new AbstractComponent("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. + } + }; - @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.start(new DefaultScope(component.getProvidedInterfaces())); + } catch (SystemAssemblyException e) { + //e.printStackTrace(); + return; + } + + fail(); + } + + /** + * DOCUMENT ME! + */ + public void testUnexpectedServicesStarted() { + try { Component component = new AbstractComponent("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 Object doStart(Scope aScope) { + addInterface(new DefaultProvidedInterface("x", + Integer.class), 100, aScope); + + return null; + } + + @Override + protected void doStop(Object aRuntime) { + // Empty. + } + }; - @Override - protected void doStop(Object aRuntime) { - // Empty. - } - }; component.start(new DefaultScope(component.getProvidedInterfaces())); } catch (SystemAssemblyException e) { //e.printStackTrace(); return; } + fail(); - } + } } diff --git a/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java b/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java index 5bfca072..611d5cf5 100644 --- a/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java +++ b/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java @@ -1,96 +1,135 @@ /* * 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 junit.framework.TestCase; 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; +import java.io.Serializable; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DefaultInterfaceDescriptorTest extends TestCase { + /** + * DOCUMENT ME! + */ + public void testOneRequiredOneProvidedMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + String.class); + RequiredInterface required = new DefaultRequiredInterface("name", + String.class); + assertTrue(required.implementedBy(provided)); + } + + /** + * DOCUMENT ME! + */ + public void testOneRequiredOneProvidedMatchSubClass() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + Integer.class); + RequiredInterface required = new DefaultRequiredInterface("name", + Number.class); + assertTrue(required.implementedBy(provided)); + } + + /** + * DOCUMENT ME! + */ + public void testOneRequiredOneProvidedNoMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + String.class); + RequiredInterface required = new DefaultRequiredInterface("name", + Number.class); + assertFalse(required.implementedBy(provided)); + } + + /** + * DOCUMENT ME! + */ + 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)); + } + + /** + * DOCUMENT ME! + */ + 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)); + } + + /** + * DOCUMENT ME! + */ + 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)); + } + + /** + * DOCUMENT ME! + */ + 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)); + } + + /** + * DOCUMENT ME! + */ + 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)); + } - 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)); - } - + private static class MyMultiple implements Runnable, Serializable { + @Override + public void run() { + // Empty + } + } } diff --git a/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java b/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java index 139de7d3..a495615f 100644 --- a/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java +++ b/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -17,11 +17,19 @@ package org.wamblee.system.core; import junit.framework.TestCase; -public class DefaultRequiredInterfaceTest extends TestCase { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class DefaultRequiredInterfaceTest extends TestCase { + /** + * DOCUMENT ME! + */ public void testEquals() { - assertFalse(new DefaultRequiredInterface("a", String.class) - .equals(new DefaultRequiredInterface("a", String.class))); + assertFalse(new DefaultRequiredInterface("a", String.class).equals( + new DefaultRequiredInterface("a", String.class))); } - } diff --git a/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java b/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java index 7199c6fb..311694aa 100644 --- a/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java +++ b/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java @@ -1,47 +1,65 @@ /* * 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; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DefaultScopeTest extends TestCase { - - public void testLookup() { - ProvidedInterface provider = new DefaultProvidedInterface("x", Integer.class); - Scope scope = new DefaultScope(new ProvidedInterface[0]); - + /** + * DOCUMENT ME! + */ + 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()); + 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]); - + + /** + * DOCUMENT ME! + */ + 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); - + + 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)); - } + assertEquals(100, + child.getInterfaceImplementation(provider1, Integer.class).intValue()); + assertEquals("hallo", + child.getInterfaceImplementation(provider2, String.class)); + } } diff --git a/system/general/src/test/java/org/wamblee/system/core/Environment.java b/system/general/src/test/java/org/wamblee/system/core/Environment.java index c202d1ab..ef5212d0 100644 --- a/system/general/src/test/java/org/wamblee/system/core/Environment.java +++ b/system/general/src/test/java/org/wamblee/system/core/Environment.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,78 +15,154 @@ */ 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; +import javax.sql.DataSource; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class Environment extends AbstractComponent { + /** + * DOCUMENT ME! + */ + private static int COUNT = 0; + + /** + * DOCUMENT ME! + */ + private EventTracker tracker; - 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 tracker; - private double random; - private int integer; - - public Environment() { - this("environment"); - } - - public Environment(String aName) { - this(aName, ""); + /** + * DOCUMENT ME! + */ + private double random; + + /** + * DOCUMENT ME! + */ + private int integer; + + /** + * Creates a new Environment object. + */ + public Environment() { + this("environment"); + } + + /** + * Creates a new Environment object. + * + * @param aName DOCUMENT ME! + */ + public Environment(String aName) { + this(aName, ""); } - - public Environment(String aName, String aPrefix) { + + /** + * Creates a new Environment object. + * + * @param aName DOCUMENT ME! + * @param aPrefix DOCUMENT ME! + */ + public Environment(String aName, String aPrefix) { super(aName, provided(aPrefix), new RequiredInterface[0]); - random = Math.random(); - integer = COUNT++; + random = Math.random(); + integer = COUNT++; + } + + /** + * Creates a new Environment object. + * + * @param aTracker DOCUMENT ME! + */ + public Environment(EventTracker aTracker) { + this(); + tracker = aTracker; } + /** + * DOCUMENT ME! + * + * @param aPrefix DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static final ProvidedInterface[] provided(String aPrefix) { + return new ProvidedInterface[] { + new DefaultProvidedInterface(aPrefix + "datasource", String.class), + new DefaultProvidedInterface(aPrefix + "integer", Integer.class) + }; + } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Integer getInteger() { + return integer; + } - 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); - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getString() { + return getName() + ".hello"; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + protected Object doStart(Scope aScope) { + addInterface(getProvidedInterfaces().get(0), getString(), aScope); + addInterface(getProvidedInterfaces().get(1), getInteger(), aScope); + track("start." + getName()); + + return random; + } + + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + protected void doStop(Object aRuntime) { + track("stop." + getName()); + + if (random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + random + " but got " + aRuntime); + } + } + + /** + * DOCUMENT ME! + * + * @param aString DOCUMENT ME! + */ + private void track(String aString) { + if (tracker == null) { + return; + } + + tracker.eventOccurred(aString); + } } diff --git a/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java b/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java index 23685e4e..83616744 100644 --- a/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java +++ b/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,68 +15,132 @@ */ 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; +import javax.sql.DataSource; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class IntegerComponent extends AbstractComponent { + /** + * DOCUMENT ME! + */ + private EventTracker tracker; - private static final ProvidedInterface[] provided(String aPrefix) { - return new ProvidedInterface[] { - new DefaultProvidedInterface(aPrefix + "integer", Integer.class) }; - } + /** + * DOCUMENT ME! + */ + private double random; - private EventTracker tracker; - private double random; + /** + * Creates a new IntegerComponent object. + */ + public IntegerComponent() { + this("environment"); + } - public IntegerComponent() { - this("environment"); - } - - public IntegerComponent(String aName) { - this(aName, ""); + /** + * Creates a new IntegerComponent object. + * + * @param aName DOCUMENT ME! + */ + public IntegerComponent(String aName) { + this(aName, ""); } - - public IntegerComponent(String aName, String aPrefix) { + + /** + * Creates a new IntegerComponent object. + * + * @param aName DOCUMENT ME! + * @param aPrefix DOCUMENT ME! + */ + public IntegerComponent(String aName, String aPrefix) { super(aName, provided(aPrefix), new RequiredInterface[0]); random = Math.random(); } + /** + * Creates a new IntegerComponent object. + * + * @param aTracker DOCUMENT ME! + */ + public IntegerComponent(EventTracker aTracker) { + this(); + tracker = aTracker; + } + + /** + * DOCUMENT ME! + * + * @param aPrefix DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static final ProvidedInterface[] provided(String aPrefix) { + return new ProvidedInterface[] { + new DefaultProvidedInterface(aPrefix + "integer", Integer.class) + }; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Integer getInteger() { + return 2; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + protected Object doStart(Scope aScope) { + addInterface(getProvidedInterfaces().get(1), getInteger(), aScope); + track("start." + getName()); + + return random; + } + + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + protected void doStop(Object aRuntime) { + track("stop." + getName()); + if (random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + random + " but got " + aRuntime); + } + } - 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); - } + /** + * DOCUMENT ME! + * + * @param aString DOCUMENT ME! + */ + private void track(String aString) { + if (tracker == null) { + return; + } + + tracker.eventOccurred(aString); + } } diff --git a/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java b/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java index 404fec70..7e8d6605 100644 --- a/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java +++ b/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java @@ -1,28 +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.core; import java.util.Comparator; -public class RequiredInterfaceComparator implements - Comparator { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class RequiredInterfaceComparator implements Comparator { + /** + * DOCUMENT ME! + * + * @param aO1 DOCUMENT ME! + * @param aO2 DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public int compare(RequiredInterface aO1, RequiredInterface aO2) { return aO1.getName().compareTo(aO2.getName()); } - } diff --git a/system/general/src/test/java/org/wamblee/system/core/StringComponent.java b/system/general/src/test/java/org/wamblee/system/core/StringComponent.java index a55d68de..54766f18 100644 --- a/system/general/src/test/java/org/wamblee/system/core/StringComponent.java +++ b/system/general/src/test/java/org/wamblee/system/core/StringComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,72 +15,141 @@ */ 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; +import javax.sql.DataSource; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class StringComponent extends AbstractComponent { + /** + * DOCUMENT ME! + */ + private EventTracker tracker; - private static final ProvidedInterface[] provided(String aPrefix) { - return new ProvidedInterface[] { - new DefaultProvidedInterface(aPrefix + "datasource", String.class) }; - } + /** + * DOCUMENT ME! + */ + private double random; - private EventTracker tracker; - private double random; + /** + * Creates a new StringComponent object. + */ + public StringComponent() { + this("environment"); + } - public StringComponent() { - this("environment"); - } - - public StringComponent(String aName) { - this(aName, ""); + /** + * Creates a new StringComponent object. + * + * @param aName DOCUMENT ME! + */ + public StringComponent(String aName) { + this(aName, ""); } - - public StringComponent(String aName, String aPrefix) { + + /** + * Creates a new StringComponent object. + * + * @param aName DOCUMENT ME! + * @param aPrefix DOCUMENT ME! + */ + public StringComponent(String aName, String aPrefix) { super(aName, provided(aPrefix), new RequiredInterface[0]); random = Math.random(); } + /** + * Creates a new StringComponent object. + * + * @param aTracker DOCUMENT ME! + */ + public StringComponent(EventTracker aTracker) { + this(); + tracker = aTracker; + } + + /** + * DOCUMENT ME! + * + * @param aPrefix DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private static final ProvidedInterface[] provided(String aPrefix) { + return new ProvidedInterface[] { + new DefaultProvidedInterface(aPrefix + "datasource", String.class) + }; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Integer getInteger() { + return 2; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String getString() { + return getName() + ".hello"; + } + + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + protected Object doStart(Scope aScope) { + addInterface(getProvidedInterfaces().get(0), getString(), aScope); + track("start." + getName()); + return 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); - } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + protected void doStop(Object aRuntime) { + track("stop." + getName()); + + if (random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + random + " but got " + aRuntime); + } + } + + /** + * DOCUMENT ME! + * + * @param aString DOCUMENT ME! + */ + private void track(String aString) { + if (tracker == null) { + return; + } + + tracker.eventOccurred(aString); + } } diff --git a/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java b/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java index 96fd009a..c2bcda5e 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java +++ b/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java @@ -1,23 +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.graph; +import junit.framework.TestCase; 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; @@ -27,75 +27,116 @@ import org.wamblee.system.core.RequiredInterface; import org.wamblee.system.graph.component.ProvidedInterfaceNode; import org.wamblee.system.graph.component.RequiredInterfaceNode; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class CompositeEdgeFilterTest extends TestCase { - private Application app = new Application(); + /** + * DOCUMENT ME! + */ + private Application app = new Application(); + + /** + * DOCUMENT ME! + */ private Environment env = new Environment(); - - private Edge createEdge(Component aClient, RequiredInterface aRequired, - Component aServer, ProvidedInterface aProvided) { + + /** + * DOCUMENT ME! + * + * @param aClient DOCUMENT ME! + * @param aRequired DOCUMENT ME! + * @param aServer DOCUMENT ME! + * @param aProvided DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private Edge createEdge(Component aClient, RequiredInterface aRequired, + Component aServer, ProvidedInterface aProvided) { Node from = new RequiredInterfaceNode(aClient, aRequired); - Node to = new ProvidedInterfaceNode(aServer, aProvided); + 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)))); + /** + * DOCUMENT ME! + */ + public void testEmpty() { + EdgeFilter restriction = new CompositeEdgeFilter(); + assertFalse(restriction.isViolated(createEdge(app, + app.getRequiredInterfaces().get(0), env, + env.getProvidedInterfaces().get(0)))); } - + + /** + * DOCUMENT ME! + * + * @param base DOCUMENT ME! + * @param aResult DOCUMENT ME! + */ private void configureRestriction(EdgeFilter base, boolean aResult) { - stub(base.isViolated((Edge)anyObject())).toReturn(aResult); + stub(base.isViolated((Edge) anyObject())).toReturn(aResult); } - - public void testOneRestriction() { - EdgeFilter base = mock(EdgeFilter.class); + + /** + * DOCUMENT ME! + */ + 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)))); - + + 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)))); + + assertTrue(composite.isViolated(createEdge(app, + app.getRequiredInterfaces().get(0), env, + env.getProvidedInterfaces().get(0)))); } - - - public void testTwoRestrictions() { - EdgeFilter base1 = mock(EdgeFilter.class); + /** + * DOCUMENT ME! + */ + 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)))); - + 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)))); - + + 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)))); + assertTrue(composite.isViolated(createEdge(app, + app.getRequiredInterfaces().get(0), env, + env.getProvidedInterfaces().get(0)))); } - } diff --git a/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java b/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java index 675a06bd..ceae5819 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java +++ b/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,17 +15,25 @@ */ package org.wamblee.system.graph; -import java.util.Arrays; -import java.util.List; - +import junit.framework.TestCase; import static org.mockito.Mockito.*; + import org.wamblee.test.AssertionUtils; +import java.util.Arrays; +import java.util.List; -import junit.framework.TestCase; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class GraphTest extends TestCase { - + /** + * DOCUMENT ME! + */ public void testNodeMgt() { final Graph graph = new Graph(); assertTrue(graph.getNodes().isEmpty()); @@ -42,128 +50,147 @@ public class GraphTest extends TestCase { // Empty node set. assertFalse(graph.removeNode(x)); - - Node y = new DefaultNode("y"); - graph.addNodes(Arrays.asList(new Node[] { x, y} )); + + 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); + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + graph.addNode(new DefaultNode("x")); + } + }, IllegalArgumentException.class); } - public void testEdgeMgt() { + /** + * DOCUMENT ME! + */ + public void testEdgeMgt() { final Graph graph = new Graph(); - final Node x = new DefaultNode("x"); - final Node y = new DefaultNode("y"); + 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); + + 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); - + 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); - - + 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) })); + 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"})); + + /** + * DOCUMENT ME! + */ + 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 edges = graph.getEdges(); + + List edges = graph.getEdges(); assertEquals(12, edges.size()); // 2 outgoing and 2 incoming nodes. } - - public void testApplyFilter() { - Graph graph = new Graph(); + + /** + * DOCUMENT ME! + */ + 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; + + graph.applyFilter(new EdgeFilter() { + @Override + public boolean isViolated(Edge aEdge) { + if (aEdge.getFrom().getName().equals("x")) { + return false; + } + + return true; } - return true; - } - }); - + }); + assertEquals(1, graph.getEdges().size()); assertEquals("x", graph.getEdges().get(0).getFrom().getName()); - } - - public void testFindIncomingOutgoing() { + + /** + * DOCUMENT ME! + */ + public void testFindIncomingOutgoing() { Graph graph = new Graph(); - Node x = new DefaultNode("x"); - Node y = new DefaultNode("y"); + Node x = new DefaultNode("x"); + Node y = new DefaultNode("y"); graph.addNode(x); graph.addNode(y); - Edge e = new DefaultEdge(x,y); + + Edge e = new DefaultEdge(x, y); graph.addEdge(e); - + List incoming = graph.findIncoming(x); - assertTrue(incoming.isEmpty()); + assertTrue(incoming.isEmpty()); + List 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()); + assertTrue(outgoing.isEmpty()); } - + + /** + * DOCUMENT ME! + */ public void testAccept() { - Graph graph = new Graph(); - Node x = new DefaultNode("x"); - Node y = new DefaultNode("y"); - Edge e = new DefaultEdge(x, y); + 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); - + + 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/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java b/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java index daddccd6..c2e5747d 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java +++ b/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java @@ -1,41 +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.graph; import java.util.ArrayList; import java.util.List; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class MyEdgeFactory implements EdgeFactory { - - public MyEdgeFactory() { + /** + * Creates a new MyEdgeFactory object. + */ + public MyEdgeFactory() { // Empty. } + /** + * DOCUMENT ME! + * + * @param aFrom DOCUMENT ME! + * @param aTo DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public List create(MyNode aFrom, MyNode aTo) { List result = new ArrayList(); - for (String fromPort: aFrom.getPorts()) { - for (String toPort: aTo.getPorts()) { - if ( fromPort.equals(toPort)) { + + for (String fromPort : aFrom.getPorts()) { + for (String toPort : aTo.getPorts()) { + if (fromPort.equals(toPort)) { result.add(new DefaultEdge(aFrom, aTo)); } } } - - return result; - } + return result; + } } diff --git a/system/general/src/test/java/org/wamblee/system/graph/MyNode.java b/system/general/src/test/java/org/wamblee/system/graph/MyNode.java index 9b5e2e46..cb6cced7 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/MyNode.java +++ b/system/general/src/test/java/org/wamblee/system/graph/MyNode.java @@ -1,29 +1,48 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class MyNode extends DefaultNode { + /** + * DOCUMENT ME! + */ + private String[] ports; - private String[] ports; - + /** + * Creates a new MyNode object. + * + * @param aName DOCUMENT ME! + * @param aPorts DOCUMENT ME! + */ public MyNode(String aName, String[] aPorts) { super(aName); - ports = aPorts; + ports = aPorts; } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ public String[] getPorts() { return ports; } diff --git a/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java b/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java index eb4deaff..e85c201c 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java +++ b/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -26,69 +26,112 @@ import org.wamblee.system.graph.DefaultNode; import org.wamblee.system.graph.Edge; import org.wamblee.system.graph.EdgeFilter; -public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase { + /** + * DOCUMENT ME! + */ private Container container; + + /** + * DOCUMENT ME! + */ private Component internal; + + /** + * DOCUMENT ME! + */ private String externalInterfaceName; + + /** + * DOCUMENT ME! + */ private String internalComponentName; + + /** + * DOCUMENT ME! + */ private String internalInterfaceName; + + /** + * DOCUMENT ME! + */ private Edge edge; + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @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))); + 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))); } + /** + * DOCUMENT ME! + */ public void testWrongExternal() { - EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( - externalInterfaceName + "x", internalComponentName, - internalInterfaceName); + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName + + "x", internalComponentName, internalInterfaceName); assertFalse(filter.isViolated(edge)); } + /** + * DOCUMENT ME! + */ public void testRightExternalWrongComponent() { - EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( - externalInterfaceName, internalComponentName + "x", - internalInterfaceName); + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName, + internalComponentName + "x", internalInterfaceName); assertTrue(filter.isViolated(edge)); } + /** + * DOCUMENT ME! + */ public void testRightExternalWrongInternal() { - EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( - externalInterfaceName, internalComponentName, - internalInterfaceName + "x"); + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName, + internalComponentName, internalInterfaceName + "x"); assertTrue(filter.isViolated(edge)); } - - public void testEverythingRight() { - EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( - externalInterfaceName, internalComponentName, - internalInterfaceName); + + /** + * DOCUMENT ME! + */ + public void testEverythingRight() { + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName, + internalComponentName, internalInterfaceName); assertFalse(filter.isViolated(edge)); } - + /** + * DOCUMENT ME! + */ public void testWrongEdgeType() { - EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( - externalInterfaceName, internalComponentName, - internalInterfaceName); - DefaultEdge edge = new DefaultEdge(new DefaultNode("x"), + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter(externalInterfaceName, + internalComponentName, internalInterfaceName); + DefaultEdge edge = new DefaultEdge(new DefaultNode("x"), new DefaultNode("y")); assertFalse(filter.isViolated(edge)); } - } diff --git a/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java b/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java index bca6303a..4204b141 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java +++ b/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -27,59 +27,97 @@ import org.wamblee.system.graph.Edge; import org.wamblee.system.graph.EdgeFilter; import org.wamblee.system.graph.Node; -public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase { + /** + * DOCUMENT ME! + */ private Component comp; + + /** + * DOCUMENT ME! + */ private Container container; + + /** + * DOCUMENT ME! + */ private Edge edge; + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @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)); + 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); + edge = new DefaultEdge(req, external); } + /** + * DOCUMENT ME! + */ public void testRightComponentRightInterface() { - EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( - comp.getName(), comp.getRequiredInterfaces().get(0).getName(), + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp + .getName(), comp.getRequiredInterfaces().get(0).getName(), container.getRequiredInterfaces().get(0).getName()); assertFalse(filter.isViolated(edge)); } + /** + * DOCUMENT ME! + */ public void testWrongInterface() { - EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( - comp.getName(), comp.getRequiredInterfaces().get(0).getName() - + "xx", container.getRequiredInterfaces().get(0).getName()); + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp + .getName(), + comp.getRequiredInterfaces().get(0).getName() + "xx", + container.getRequiredInterfaces().get(0).getName()); assertFalse(filter.isViolated(edge)); } + /** + * DOCUMENT ME! + */ public void testWrongComponent() { - EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( - comp.getName() + "xx", comp.getRequiredInterfaces().get(0) - .getName(), container.getRequiredInterfaces().get(0) - .getName()); + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp + .getName() + "xx", + comp.getRequiredInterfaces().get(0).getName(), + container.getRequiredInterfaces().get(0).getName()); assertFalse(filter.isViolated(edge)); } + /** + * DOCUMENT ME! + */ public void testWrongExternalInterface() { - EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( - comp.getName(), comp.getRequiredInterfaces().get(0).getName(), + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp + .getName(), comp.getRequiredInterfaces().get(0).getName(), container.getRequiredInterfaces().get(0).getName() + "xx"); assertTrue(filter.isViolated(edge)); } + /** + * DOCUMENT ME! + */ public void testWrongEdgeType() { - DefaultEdge edge = new DefaultEdge(new DefaultNode("x"), + DefaultEdge edge = new DefaultEdge(new DefaultNode("x"), new DefaultNode("y")); - EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( - comp.getName(), comp.getRequiredInterfaces().get(0).getName(), + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter(comp + .getName(), comp.getRequiredInterfaces().get(0).getName(), container.getRequiredInterfaces().get(0).getName()); assertFalse(filter.isViolated(edge)); } diff --git a/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java b/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java index 88f29b8d..1b6ff0c2 100644 --- a/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java +++ b/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java @@ -1,23 +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.component; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import junit.framework.TestCase; import org.wamblee.system.container.Application; import org.wamblee.system.core.Environment; @@ -25,79 +23,118 @@ 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; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; -public class ConnectRequiredProvidedEdgeFilterTest extends TestCase { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ConnectRequiredProvidedEdgeFilterTest extends TestCase { + /** + * DOCUMENT ME! + */ private Application app1 = new Application("app1", "pf1."); + + /** + * DOCUMENT ME! + */ private Application app2 = new Application("app2", "pf2."); - + + /** + * DOCUMENT ME! + */ private Environment env1 = new Environment("env1", "pf3."); + + /** + * DOCUMENT ME! + */ private Environment env2 = new Environment("env2", "pf4."); - - - private void compare(Boolean[] aExpected, EdgeFilter aRestriction) { - List result = new ArrayList(); - - - - // 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); + + /** + * DOCUMENT ME! + * + * @param aExpected DOCUMENT ME! + * @param aRestriction DOCUMENT ME! + */ + private void compare(Boolean[] aExpected, EdgeFilter aRestriction) { + List result = new ArrayList(); + + // 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() { + /** + * DOCUMENT ME! + */ + public void testNoRestriction() { AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { - @Override - public void run() throws Exception { - EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, null, null); - - } - }, IllegalArgumentException.class); + @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); + @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); + + /** + * DOCUMENT ME! + */ + 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); + + /** + * DOCUMENT ME! + */ + 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); - + + /** + * DOCUMENT ME! + */ + 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/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java b/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java index 7443b57c..34dae177 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java @@ -1,30 +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.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); +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ConfiguredProperties extends Properties { +/** + * Creates a new ConfiguredProperties object. + * + * @param aProps DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + public ConfiguredProperties(String aProps) throws IOException { + InputStream is = new ByteArrayInputStream(aProps.getBytes()); + load(is); is.close(); } } diff --git a/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java b/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java index f88c4054..c21fe9ce 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java @@ -1,51 +1,60 @@ /* * 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; +import java.util.Properties; + + /** - * Bean that provides postprocessing of the bean factory based on - * a given set of properties. - * + * 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)); + } - /** - * Constructs the property setter. - * @param aProps Properties. - */ - public PropertySetter(Properties aProps) { - String propFile = createPropertyFile(aProps); - setLocation(new StringResource(propFile)); - } - + /** + * DOCUMENT ME! + * + * @param aProps DOCUMENT ME! + * + * @return DOCUMENT ME! + */ 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"); - } + 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/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java b/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java index 71ac3085..b037a294 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java @@ -1,65 +1,90 @@ /* * 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; +import java.util.List; + + /** - * Bean which adds a service required by the spring component to - * the application context so that other spring beans can use it. - * + * 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 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 + "'"); - } + /** + * DOCUMENT ME! + */ + private RequiredInterface _required; + +/** + * Constructs the bean. + * @param aId Id of the bean in the service registry. + */ + public RequiredServiceBean(String aId) { + List required = SpringComponent.THIS.get() + .getRequiredInterfaces(); + + for (RequiredInterface intf : required) { + if (intf.getName().equals(aId)) { + _required = intf; + + return; + } + } - @Override - public Object getObject() throws Exception { - return SpringComponent.SCOPE.get().getInterfaceImplementation( - _required.getProvider(), Object.class); - } + throw new SystemAssemblyException("Cannot resolve required component '" + + aId + "'"); + } - @Override - public Class getObjectType() { - return null; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ + @Override + public Object getObject() throws Exception { + return SpringComponent.SCOPE.get() + .getInterfaceImplementation(_required.getProvider(), Object.class); + } - @Override - public boolean isSingleton() { - return true; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public Class getObjectType() { + return null; + } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean isSingleton() { + return true; + } } diff --git a/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java b/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java index 0e4c62eb..ad6c4b0f 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java @@ -1,31 +1,29 @@ /* * 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; @@ -33,170 +31,267 @@ import org.wamblee.system.core.RequiredInterface; import org.wamblee.system.core.Scope; import org.wamblee.system.core.SystemAssemblyException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + + /** - * Represents a system configured based on spring. The spring config files that - * are configured should not contain any PropertyPlaceholderConfigurer objects. - * + * 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 { + /** + * DOCUMENT ME! + */ + private static final String CONTEXT_KEY = "context"; + + /** + * DOCUMENT ME! + */ + static final ThreadLocal THIS = new ThreadLocal(); + + /** + * DOCUMENT ME! + */ + static final ThreadLocal SCOPE = new ThreadLocal(); + + /** + * DOCUMENT ME! + */ + private Properties properties; - private static final String CONTEXT_KEY = "context"; - - static final ThreadLocal THIS = new ThreadLocal(); - static final ThreadLocal SCOPE = new ThreadLocal(); - - private Properties properties; - private String[] configFiles; - private Map provided; - private Map required; - private Map 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 aProvided, - Map 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(); - - } - - /** - * 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 requiredIntf: getRequiredInterfaces()) { - String beanName = required.get(requiredIntf); - if ( beanName != null && beanName.length() > 0) { - ConstructorArgumentValues cargs = new ConstructorArgumentValues(); - cargs.addGenericArgumentValue(requiredIntf.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()) { + /** + * DOCUMENT ME! + */ + private String[] configFiles; + + /** + * DOCUMENT ME! + */ + private Map provided; + + /** + * DOCUMENT ME! + */ + private Map required; + + /** + * DOCUMENT ME! + */ + private Map 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 aProvided, + Map 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(); + } + + /** + * 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); + } + + /** + * DOCUMENT ME! + * + * @param aProperties DOCUMENT ME! + */ + public void addProperties(Properties aProperties) { + for (Object key : aProperties.keySet()) { + setProperty((String) key, aProperties.getProperty((String) key)); + } + } + + /** + * DOCUMENT ME! + * + * @param aBeanname DOCUMENT ME! + * @param aProperties DOCUMENT ME! + */ + public void addProperties(String aBeanname, Properties aProperties) { + propertyObjects.put(aBeanname, aProperties); + } + + /** + * DOCUMENT ME! + * + * @param aBeanname DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Properties getProperties(String aBeanname) { + return propertyObjects.get(aBeanname); + } + + /** + * DOCUMENT ME! + * + * @param aExternalScope DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SystemAssemblyException DOCUMENT ME! + */ + @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); + } + } + + /** + * DOCUMENT ME! + * + * @param aContext DOCUMENT ME! + * @param aScope DOCUMENT ME! + * + * @throws IllegalArgumentException DOCUMENT ME! + */ + 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); + } + } + + /** + * DOCUMENT ME! + * + * @param aParentContext DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private AbstractApplicationContext parseConfigFiles( + GenericApplicationContext aParentContext) { + // Parse spring config files + return new ClassPathXmlApplicationContext((String[]) configFiles, + false, aParentContext); + } + + /** + * DOCUMENT ME! + * + * @param aParentContext DOCUMENT ME! + */ + private void registerRequiredServices( + GenericApplicationContext aParentContext) { + // Register required services in a parent context + for (RequiredInterface requiredIntf : getRequiredInterfaces()) { + String beanName = required.get(requiredIntf); + + if ((beanName != null) && (beanName.length() > 0)) { + ConstructorArgumentValues cargs = new ConstructorArgumentValues(); + cargs.addGenericArgumentValue(requiredIntf.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. + } + } + } + + /** + * DOCUMENT ME! + * + * @param aParentContext DOCUMENT ME! + */ + 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()); + 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(); - } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ + @Override + protected void doStop(Scope aRuntime) { + AbstractApplicationContext context = (AbstractApplicationContext) aRuntime + .get(CONTEXT_KEY); + context.close(); + } } diff --git a/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java b/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java index 3f9a7919..5429d6cd 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java @@ -1,74 +1,139 @@ /* * 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 org.springframework.core.io.Resource; + 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ class StringResource implements Resource { - - private String _value; - - public StringResource(String aValue) { - _value = aValue; - } + /** + * DOCUMENT ME! + */ + private String _value; - @Override - public Resource createRelative(String aRelativePath) throws IOException { - throw new IOException("No relative resource possible"); - } +/** + * Creates a new StringResource object. + * + * @param aValue DOCUMENT ME! + */ + public StringResource(String aValue) { + _value = aValue; + } - @Override - public boolean exists() { - return false; - } + /** + * DOCUMENT ME! + * + * @param aRelativePath DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + @Override + public Resource createRelative(String aRelativePath) + throws IOException { + throw new IOException("No relative resource possible"); + } - @Override - public String getDescription() { - return "Properties of a spring component"; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean exists() { + return false; + } - @Override - public File getFile() throws IOException { - throw new IOException(); - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getDescription() { + return "Properties of a spring component"; + } - @Override - public String getFilename() { - return "springcomponent.properties"; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + @Override + public File getFile() throws IOException { + throw new IOException(); + } - @Override - public URL getURL() throws IOException { - throw new IOException(); - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public String getFilename() { + return "springcomponent.properties"; + } - @Override - public boolean isOpen() { - return false; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + @Override + public URL getURL() throws IOException { + throw new IOException(); + } - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(_value.getBytes()); - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + @Override + public boolean isOpen() { + return false; + } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(_value.getBytes()); + } } diff --git a/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java b/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java index a8d53d46..1b121bca 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,15 +15,10 @@ */ 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; @@ -34,43 +29,89 @@ import org.wamblee.system.core.RequiredInterface; import org.wamblee.system.core.Scope; import org.wamblee.system.spring.SpringComponent; +import java.io.IOException; + +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + +import javax.sql.DataSource; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DatasourceComponent extends AbstractComponent { + /** + * DOCUMENT ME! + */ + private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops", + Properties.class); - private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops", Properties.class); - private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface("datasource", + /** + * DOCUMENT ME! + */ + private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface("datasource", DataSource.class); + + /** + * DOCUMENT ME! + */ private static ProvidedInterface ORM_CONFIG = new DefaultProvidedInterface("ormconfig", ORMappingConfig.class); - + +/** + * Creates a new DatasourceComponent object. + * + * @param aName DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public DatasourceComponent(String aName) throws IOException { - super(aName); - + super(aName); + addRequiredInterface(PROPS); addProvidedInterface(DATASOURCE); addProvidedInterface(ORM_CONFIG); } - + /** + * DOCUMENT ME! + * + * @param aScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected DataSource doStart(Scope aScope) { - Properties dbProps = aScope.getInterfaceImplementation( - PROPS.getProvider(), Properties.class); - DriverManagerDataSource ds = new DriverManagerDataSource( - dbProps.getProperty("database.url"), + 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; + 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; } + /** + * DOCUMENT ME! + * + * @param aRuntime DOCUMENT ME! + */ @Override protected void doStop(DataSource aRuntime) { - // Empty. + // Empty. } } diff --git a/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java b/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java index 4b256254..ad5c1d2e 100644 --- a/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java +++ b/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java @@ -1,33 +1,31 @@ /* * 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; @@ -37,69 +35,137 @@ import org.wamblee.system.core.RequiredInterface; import org.wamblee.system.core.Scope; import org.wamblee.system.spring.SpringComponent; -public class HibernateComponent extends SpringComponent { +import java.io.IOException; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.sql.DataSource; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class HibernateComponent extends SpringComponent { + /** + * DOCUMENT ME! + */ private static final String HIBERNATE_DIALECT_PROP = "hibernate.dialect"; + + /** + * DOCUMENT ME! + */ private static final String HIBERNATE_SCHEMAUPDATE_PROP = "hibernate.schemaupdate"; + + /** + * DOCUMENT ME! + */ private static final String HIBERNATE_PROPS_KEY = "hibernateProperties"; + + /** + * DOCUMENT ME! + */ 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(); + + /** + * DOCUMENT ME! + */ + private final RequiredInterface CONFIG = new DefaultRequiredInterface("config", + ORMappingConfig.class); + +/** + * Creates a new HibernateComponent object. + * + * @param aName DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + 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); } - + + /** + * DOCUMENT ME! + * + * @param aExternalScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected Scope doStart(Scope aExternalScope) { - - ORMappingConfig config = aExternalScope.getInterfaceImplementation(CONFIG.getProvider(), ORMappingConfig.class); + 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() { - @Override - public String handleMySqlInnoDb() { - return MySQLInnoDBDialect.class.getName(); - } - @Override - public String handleDerby() { - return DerbyDialect.class.getName(); - } - }); + + DatabaseType db = config.getType(); + String dialect = db.handleCases(new DatabaseType.Switch() { + @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() { + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + private Properties getHibernateProperties() { return getProperties(HIBERNATE_PROPS_KEY); } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createRequired() { - Map required = new HashMap(); - required.put(new DefaultRequiredInterface("datasource", DataSource.class), "dataSource"); - required.put(new DefaultRequiredInterface("mappingFiles", HibernateMappingFiles.class), - "hibernateMappingFiles"); + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("datasource", DataSource.class), + "dataSource"); + required.put(new DefaultRequiredInterface("mappingFiles", + HibernateMappingFiles.class), "hibernateMappingFiles"); + return required; } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private static Map createProvided() { - Map provided = new HashMap(); - - 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)); + Map provided = new HashMap(); + + 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/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java b/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java index 5715460a..966c1045 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java @@ -1,35 +1,58 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ 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"); - } + /** + * DOCUMENT ME! + */ + private HelloService hello; + +/** + * Creates a new BlaService object. + * + * @param aService DOCUMENT ME! + */ + public BlaService(HelloService aService) { + if (aService == null) { + throw new IllegalArgumentException("helloService is null"); + } + + hello = aService; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String execute() { + return hello.say(); + } + + /** + * DOCUMENT ME! + */ + public void stop() { + System.out.println("Blaservice stopping"); + } } diff --git a/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java b/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java index 00002de1..05043e37 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java @@ -1,38 +1,49 @@ /* * 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 junit.framework.TestCase; + import java.io.IOException; + import java.util.Properties; -import junit.framework.TestCase; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class ConfiguredPropertiesTest extends TestCase { - - public void testProps() throws IOException { + /** + * DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ + 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()); + 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/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java b/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java index d3b5b121..27c0bd8b 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java @@ -1,30 +1,48 @@ /* * 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; +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class HelloService { - - private String msg; - - public HelloService(String aMsg) { - SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg); - msg = aMsg; - } - - public String say() { - return msg; - } + /** + * DOCUMENT ME! + */ + private String msg; + +/** + * Creates a new HelloService object. + * + * @param aMsg DOCUMENT ME! + */ + public HelloService(String aMsg) { + SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg); + msg = aMsg; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public String say() { + return msg; + } } diff --git a/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java b/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java index 4273ca01..501e0762 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java @@ -1,12 +1,12 @@ /* * 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. @@ -17,15 +17,34 @@ package org.wamblee.system.spring; import java.util.Properties; -public class HelloService2 { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class HelloService2 { + /** + * DOCUMENT ME! + */ private Properties props; +/** + * Creates a new HelloService2 object. + * + * @param aProps DOCUMENT ME! + */ public HelloService2(Properties aProps) { props = aProps; } - public Properties getProperties() { - return props; + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public Properties getProperties() { + return props; } } diff --git a/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java b/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java index ff3aeb24..6407c144 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java @@ -1,12 +1,12 @@ /* * 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. @@ -15,15 +15,10 @@ */ 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; @@ -31,74 +26,130 @@ 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 { +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class SpringComponentTest extends TestCase { + /** + * DOCUMENT ME! + */ private static final String HELLO_SERVICE_SPRING_XML = "test.org.wamblee.system.spring.xml"; + + /** + * DOCUMENT ME! + */ private static final String HELLO_SERVICE_SPRING_WITH_REQS_XML = "test.org.wamblee.system.springWithRequirements.xml"; + + /** + * DOCUMENT ME! + */ private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML = "test.org.wamblee.system.springWithProperties.xml"; + + /** + * DOCUMENT ME! + */ private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 = "test.org.wamblee.system.springWithProperties2.xml"; + /** + * DOCUMENT ME! + */ private static final String PROPERTY_FILE = "test.org.wamblee.system.spring.properties"; + /** + * DOCUMENT ME! + */ public static EventTracker EVENT_TRACKER; + /** + * DOCUMENT ME! + */ private Scope externalScope; + /** + * DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ @Override protected void setUp() throws Exception { super.setUp(); - EVENT_TRACKER = new EventTracker(); - externalScope = new DefaultScope(new ProvidedInterface[0]); + EVENT_TRACKER = new EventTracker(); + externalScope = new DefaultScope(new ProvidedInterface[0]); } + /** + * DOCUMENT ME! + */ public void testBlackboxSystem() { - SpringComponent system = new SpringComponent("system", + SpringComponent system = new SpringComponent("system", new String[] { HELLO_SERVICE_SPRING_XML }, new HashMap(), new HashMap()); - Scope runtime = system.start(externalScope); - assertEquals(0, externalScope.getProvidedInterfaces().size()); + Scope runtime = system.start(externalScope); + assertEquals(0, externalScope.getProvidedInterfaces().size()); system.stop(runtime); } + /** + * DOCUMENT ME! + */ public void testOneProvidedService() { Map provided = new HashMap(); - provided.put("helloService", new DefaultProvidedInterface("hello", - HelloService.class)); + provided.put("helloService", + new DefaultProvidedInterface("hello", HelloService.class)); - SpringComponent system = new SpringComponent("system", + SpringComponent system = new SpringComponent("system", new String[] { HELLO_SERVICE_SPRING_XML }, provided, new HashMap()); - Scope runtime = system.start(externalScope); + Scope runtime = system.start(externalScope); List 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); + Object service2 = externalScope.getInterfaceImplementation(provided.get( + "helloService"), Object.class); assertSame(service, service2); assertEquals("Hello world!", ((HelloService) service).say()); system.stop(runtime); } + /** + * DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public void testWithProperties() throws IOException { Map provided = new HashMap(); - provided.put("helloService", new DefaultProvidedInterface("hello", - HelloService.class)); + provided.put("helloService", + new DefaultProvidedInterface("hello", HelloService.class)); + SpringComponent system = new SpringComponent("system", new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML }, provided, new HashMap()); - Properties props = new Properties(); + Properties props = new Properties(); props.load(new ClassPathResource(PROPERTY_FILE).getInputStream()); system.addProperties(props); @@ -107,31 +158,42 @@ public class SpringComponentTest extends TestCase { // unprocessed property // and another time with the processed property. assertEquals(1, EVENT_TRACKER.getEventCount()); + List services = scope.getProvidedInterfaces(); - assertEquals("Property Value", scope.getInterfaceImplementation( - services.get(0), HelloService.class).say()); + assertEquals("Property Value", + scope.getInterfaceImplementation(services.get(0), HelloService.class) + .say()); } + /** + * DOCUMENT ME! + * + * @throws IOException DOCUMENT ME! + */ public void testWithPropertiesAsBean() throws IOException { Map provided = new HashMap(); - provided.put("helloService", new DefaultProvidedInterface("hello", - HelloService2.class)); + provided.put("helloService", + new DefaultProvidedInterface("hello", HelloService2.class)); + SpringComponent system = new SpringComponent("system", new String[] { HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 }, provided, new HashMap()); - Properties props = new Properties(); + Properties props = new Properties(); props.load(new ClassPathResource(PROPERTY_FILE).getInputStream()); system.addProperties("properties", props); - Scope scope = system.start(externalScope); + Scope scope = system.start(externalScope); List services = scope.getProvidedInterfaces(); - Properties props2 = scope.getInterfaceImplementation(services.get(0), - HelloService2.class).getProperties(); + Properties props2 = scope.getInterfaceImplementation(services + .get(0), HelloService2.class).getProperties(); assertEquals(props, props2); } + /** + * DOCUMENT ME! + */ public void testWithMissingRequirement() { try { SpringComponent system = new SpringComponent("system", @@ -143,21 +205,28 @@ public class SpringComponentTest extends TestCase { // e.printStackTrace(); return; } + fail(); } + /** + * DOCUMENT ME! + */ public void testWithRequirement() { Map required = new HashMap(); required.put(new DefaultRequiredInterface("hello", HelloService.class), - "helloService"); - SpringComponent system = new SpringComponent("system", + "helloService"); + + SpringComponent system = new SpringComponent("system", new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, new HashMap(), required); - HelloService helloObject = new HelloService("ladida"); + HelloService helloObject = new HelloService("ladida"); ProvidedInterface helloService = new DefaultProvidedInterface("hello", HelloService.class); - Scope scope = new DefaultScope(new ProvidedInterface[] { helloService }); + Scope scope = new DefaultScope(new ProvidedInterface[] { + helloService + }); scope.publishInterface(helloService, helloObject); system.getRequiredInterfaces().get(0).setProvider(helloService); @@ -165,28 +234,35 @@ public class SpringComponentTest extends TestCase { system.stop(runtime); } + /** + * DOCUMENT ME! + */ public void testWithRequirementAndProvidedService() { Map required = new HashMap(); required.put(new DefaultRequiredInterface("hello", HelloService.class), - "helloService"); + "helloService"); + Map provided = new HashMap(); - provided.put("blaService", new DefaultProvidedInterface("bla", - BlaService.class)); + provided.put("blaService", + new DefaultProvidedInterface("bla", BlaService.class)); - SpringComponent system = new SpringComponent("system", + SpringComponent system = new SpringComponent("system", new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, provided, required); - HelloService helloObject = new HelloService("ladida"); + HelloService helloObject = new HelloService("ladida"); ProvidedInterface helloService = new DefaultProvidedInterface("hello", HelloService.class); - Scope scope = new DefaultScope(new ProvidedInterface[] { helloService }); + Scope scope = new DefaultScope(new ProvidedInterface[] { + helloService + }); scope.publishInterface(helloService, helloObject); system.getRequiredInterfaces().get(0).setProvider(helloService); - Scope runtime = system.start(scope); + + Scope runtime = system.start(scope); ProvidedInterface started = runtime.getProvidedInterfaces().get(0); - Object impl = runtime.getInterfaceImplementation(started, + Object impl = runtime.getInterfaceImplementation(started, BlaService.class); assertNotNull(impl); assertTrue(impl instanceof BlaService); @@ -195,35 +271,36 @@ public class SpringComponentTest extends TestCase { } /** - * 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. + * 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 provided = new HashMap(); - provided.put("helloService", new DefaultProvidedInterface("hello", - HelloService.class)); + provided.put("helloService", + new DefaultProvidedInterface("hello", HelloService.class)); - SubSpringComponent system = new SubSpringComponent("system", + SubSpringComponent system = new SubSpringComponent("system", new String[] { HELLO_SERVICE_SPRING_XML }, provided, new HashMap()); - Scope runtime = system.start(externalScope); + Scope runtime = system.start(externalScope); List 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); + Object service2 = externalScope.getInterfaceImplementation(provided.get( + "helloService"), Object.class); assertSame(service, service2); - Object floatsvc = externalScope.getInterfaceImplementation(system - .getProvidedInterfaces().get(1), Object.class); + Object floatsvc = externalScope.getInterfaceImplementation(system.getProvidedInterfaces() + .get(1), Object.class); assertTrue(floatsvc instanceof Float); assertTrue((((Float) floatsvc).floatValue() - 100.345f) < 0.00001); @@ -232,24 +309,28 @@ public class SpringComponentTest extends TestCase { } /** - * Tests the spring component with an additional requirement from the subclass - * which is not required by the spring config files inside. + * 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 required = new HashMap(); required.put(new DefaultRequiredInterface("hello", HelloService.class), - "helloService"); - SpringComponent system = new SubSpringComponent2("system", + "helloService"); + + SpringComponent system = new SubSpringComponent2("system", new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, new HashMap(), required); - HelloService helloObject = new HelloService("ladida"); + 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 }); + + 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); @@ -257,8 +338,8 @@ public class SpringComponentTest extends TestCase { Scope runtime = system.start(scope); system.stop(runtime); - - assertEquals(100.234f, ((Float)runtime.get("floatValue")).floatValue(), 0.0001f); - } + assertEquals(100.234f, + ((Float) runtime.get("floatValue")).floatValue(), 0.0001f); + } } diff --git a/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java b/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java index 5e79a7ad..c7e2bade 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java @@ -1,44 +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.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; +import java.util.Map; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class SubSpringComponent extends SpringComponent { - - private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided", Float.class); + /** + * DOCUMENT ME! + */ + private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided", + Float.class); +/** + * Creates a new SubSpringComponent object. + * + * @param aName DOCUMENT ME! + * @param aConfigFiles DOCUMENT ME! + * @param aProvided DOCUMENT ME! + * @param aRequired DOCUMENT ME! + */ public SubSpringComponent(String aName, String[] aConfigFiles, - Map aProvided, - Map aRequired) { + Map aProvided, + Map aRequired) { super(aName, aConfigFiles, aProvided, aRequired); addProvidedInterface(PROVIDED); } - + + /** + * DOCUMENT ME! + * + * @param aExternalScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected Scope doStart(Scope aExternalScope) { - Scope scope = super.doStart(aExternalScope); addInterface(PROVIDED, 100.345f, aExternalScope); + return scope; } } diff --git a/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java b/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java index 7b67cc42..f86f258b 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java @@ -1,45 +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.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; +import java.util.Map; + + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class SubSpringComponent2 extends SpringComponent { - - private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required", Float.class); + /** + * DOCUMENT ME! + */ + private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required", + Float.class); +/** + * Creates a new SubSpringComponent2 object. + * + * @param aName DOCUMENT ME! + * @param aConfigFiles DOCUMENT ME! + * @param aProvided DOCUMENT ME! + * @param aRequired DOCUMENT ME! + */ public SubSpringComponent2(String aName, String[] aConfigFiles, - Map aProvided, - Map aRequired) { + Map aProvided, + Map aRequired) { super(aName, aConfigFiles, aProvided, aRequired); addRequiredInterface(REQUIRED); } - + + /** + * DOCUMENT ME! + * + * @param aExternalScope DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected Scope doStart(Scope aExternalScope) { - Scope scope = super.doStart(aExternalScope); - - float value = aExternalScope.getInterfaceImplementation(REQUIRED.getProvider(), Float.class); + + float value = aExternalScope.getInterfaceImplementation(REQUIRED + .getProvider(), Float.class); scope.put("floatValue", value); + return scope; } } diff --git a/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java b/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java index ac9d6f6f..09d5725b 100644 --- a/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java +++ b/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java @@ -1,51 +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.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; @@ -53,17 +50,33 @@ 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; +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; + + /** - * Test support class for database testing. Currently, this still requires the - * spring platform transaction manager and hibernate template. + * 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); + /** + * DOCUMENT ME! + */ + private static final Log LOG = LogFactory.getLog(DatabaseTesterComponent.class); /** * Schema pattern. @@ -75,21 +88,38 @@ public class DatabaseTesterComponent { */ private ApplicationContext context; + /** + * DOCUMENT ME! + */ private HibernateTemplate hibernateTemplate; + /** + * DOCUMENT ME! + */ private PlatformTransactionManager transactionManager; + /** + * DOCUMENT ME! + */ private DataSource dataSource; +/** + * Creates a new DatabaseTesterComponent object. + * + * @param aHibernateTemplate DOCUMENT ME! + * @param aTransactionManager DOCUMENT ME! + * @param aDataSource DOCUMENT ME! + */ public DatabaseTesterComponent(HibernateTemplate aHibernateTemplate, - PlatformTransactionManager aTransactionManager, - DataSource aDataSource) { - hibernateTemplate = aHibernateTemplate; - transactionManager = aTransactionManager; - dataSource = aDataSource; + PlatformTransactionManager aTransactionManager, DataSource aDataSource) { + hibernateTemplate = aHibernateTemplate; + transactionManager = aTransactionManager; + dataSource = aDataSource; } /** + * DOCUMENT ME! + * * @return Hibernate session factory. */ protected SessionFactory getSessionFactory() { @@ -98,10 +128,10 @@ public class DatabaseTesterComponent { /** * Performs common initialization for test cases: - *
      - *
    • Cleaning the database.
    • - *
    - * + *
      + *
    • Cleaning the database.
    • + *
    + * * @throws Exception */ public void setUp() throws Exception { @@ -111,9 +141,9 @@ public class DatabaseTesterComponent { } /** - * Performs common tear down after execution of a test case. Currenlty this - * method does nothing. - * + * Performs common tear down after execution of a test case. + * Currenlty this method does nothing. + * * @throws Exception */ protected void tearDown() throws Exception { @@ -121,6 +151,8 @@ public class DatabaseTesterComponent { } /** + * DOCUMENT ME! + * * @return Transaction manager */ protected PlatformTransactionManager getTransactionManager() { @@ -128,6 +160,8 @@ public class DatabaseTesterComponent { } /** + * DOCUMENT ME! + * * @return Starts a new transaction. */ protected TransactionStatus getTransaction() { @@ -140,7 +174,7 @@ public class DatabaseTesterComponent { /** * Returns the hibernate template for executing hibernate-specific * functionality. - * + * * @return Hibernate template. */ public HibernateTemplate getTemplate() { @@ -148,19 +182,17 @@ public class DatabaseTesterComponent { } /** - * Flushes the session. Should be called after some Hibernate work and - * before JDBC is used to check results. - * + * 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. - * + * 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(); @@ -170,9 +202,9 @@ public class DatabaseTesterComponent { /** * 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. - * + * 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) { @@ -181,15 +213,19 @@ public class DatabaseTesterComponent { /** * Gets the connection. - * + * * @return Connection. */ public Connection getConnection() { return DataSourceUtils.getConnection(getDataSource()); } + /** + * DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ public void cleanDatabase() throws SQLException { - if (!isDatabaseConfigured()) { return; } @@ -197,11 +233,11 @@ public class DatabaseTesterComponent { String[] tables = getTableNames(); try { - IDatabaseConnection connection = new DatabaseConnection( - getConnection()); - ITableFilter filter = new DatabaseSequenceFilter(connection, tables); - IDataSet dataset = new FilteredDataSet(filter, connection - .createDataSet(tables)); + 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) { @@ -212,42 +248,55 @@ public class DatabaseTesterComponent { } /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + * * @throws SQLException */ public String[] getTableNames() throws SQLException { - List result = new ArrayList(); LOG.debug("Getting database table names to clean (schema: '" - + SCHEMA_PATTERN + "'"); + + SCHEMA_PATTERN + "'"); + + ResultSet tables = getConnection().getMetaData() + .getTables(null, SCHEMA_PATTERN, "%", new String[] { "TABLE" }); - 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."); + + " to list of tables to be cleaned."); } } + return (String[]) result.toArray(new String[0]); } /** - * @return + * DOCUMENT ME! + * + * @param aTableList DOCUMENT ME! + * * @throws SQLException */ public void emptyTables(List aTableList) throws SQLException { Iterator liTable = aTableList.iterator(); + while (liTable.hasNext()) { emptyTable((String) liTable.next()); } } /** - * @return + * DOCUMENT ME! + * + * @param aTable DOCUMENT ME! + * * @throws SQLException */ public void emptyTable(String aTable) throws SQLException { @@ -255,7 +304,10 @@ public class DatabaseTesterComponent { } /** - * @return + * DOCUMENT ME! + * + * @param aTable DOCUMENT ME! + * * @throws SQLException */ public void dropTable(String aTable) throws SQLException { @@ -264,9 +316,9 @@ public class DatabaseTesterComponent { /** * Executes an SQL statement within a transaction. - * - * @param aSql - * SQL statement. + * + * @param aSql SQL statement. + * * @return Return code of the corresponding JDBC call. */ public int executeSql(final String aSql) { @@ -274,14 +326,13 @@ public class DatabaseTesterComponent { } /** - * Executes an SQL statement within a transaction. See - * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * 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. + * + * @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) { @@ -289,105 +340,105 @@ public class DatabaseTesterComponent { } /** - * 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. + * 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); + public Map execute() throws Exception { + JdbcTemplate template = new JdbcTemplate(getDataSource()); + int result = template.update(aSql, + aArgs); - Map map = new TreeMap(); - map.put("result", new Integer(result)); + Map map = new TreeMap(); + map.put("result", new Integer(result)); - return map; - } - }); + return map; + } + }); return ((Integer) results.get("result")).intValue(); } /** * Executes a transaction with a result. - * - * @param aCallback - * Callback to do your transactional work. + * + * @param aCallback Callback to do your transactional work. + * * @return Result. */ public Object executeTransaction(TransactionCallback aCallback) { - TransactionTemplate lTemplate = new TransactionTemplate( - getTransactionManager()); + TransactionTemplate lTemplate = new TransactionTemplate(getTransactionManager()); + return lTemplate.execute(aCallback); } /** * Executes a transaction without a result. - * - * @param aCallback - * Callback to do your transactional work. . + * + * @param aCallback Callback to do your transactional work. . */ public void executeTransaction(TransactionCallbackWithoutResult aCallback) { - TransactionTemplate template = new TransactionTemplate( - getTransactionManager()); + 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. + * 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. + * + * @throws RuntimeException DOCUMENT ME! */ 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); + 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. + * 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. + * + * @throws RuntimeException DOCUMENT ME! */ public void executeTransaction( - final TestTransactionCallbackWithoutResult aCallback) { + 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); + 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. + * + * @param aSql Query to execute. + * * @return Result set. */ public ResultSet executeQuery(String aSql) { @@ -395,14 +446,13 @@ public class DatabaseTesterComponent { } /** - * Executes a query with a single argument. See - * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * 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. + * + * @param aSql Query. + * @param aArg Argument. + * * @return Result set. */ public ResultSet executeQuery(String aSql, Object aArg) { @@ -410,21 +460,21 @@ public class DatabaseTesterComponent { } /** - * 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. + * 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. + * + * @throws RuntimeException DOCUMENT ME! */ public ResultSet executeQuery(final String aSql, final Object[] aArgs) { try { - Connection connection = getConnection(); + Connection connection = getConnection(); - PreparedStatement statement = connection.prepareStatement(aSql); + PreparedStatement statement = connection.prepareStatement(aSql); setPreparedParams(aArgs, statement); return statement.executeQuery(); @@ -434,18 +484,17 @@ public class DatabaseTesterComponent { } /** - * Sets the values of a prepared statement. See - * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * 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 + * + * @param aArgs Arguments to the prepared statement. + * @param aStatement Prepared statement + * * @throws SQLException */ private void setPreparedParams(final Object[] aArgs, - PreparedStatement aStatement) throws SQLException { + PreparedStatement aStatement) throws SQLException { for (int i = 1; i <= aArgs.length; i++) { setPreparedParam(i, aStatement, aArgs[i - 1]); } @@ -453,17 +502,15 @@ public class DatabaseTesterComponent { /** * 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. + * + * @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 { + Object aObject) throws SQLException { if (aObject instanceof Integer) { aStatement.setInt(aIndex, ((Integer) aObject).intValue()); } else if (aObject instanceof Long) { @@ -472,21 +519,29 @@ public class DatabaseTesterComponent { aStatement.setString(aIndex, (String) aObject); } else { TestCase.fail("Unsupported object type for prepared statement: " - + aObject.getClass() + " value: " + aObject - + " statement: " + aStatement); + + aObject.getClass() + " value: " + aObject + " statement: " + + aStatement); } } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ private boolean isDatabaseConfigured() { try { getDataSource(); } catch (NoSuchBeanDefinitionException e) { return false; } + return true; } /** + * DOCUMENT ME! + * * @return Returns the dataSource. */ public DataSource getDataSource() { @@ -494,20 +549,34 @@ public class DatabaseTesterComponent { } /** + * DOCUMENT ME! + * + * @param aTable DOCUMENT ME! + * * @return + * * @throws SQLException */ public int getTableSize(final String aTable) throws SQLException { - ResultSet resultSet = executeQuery("select * from " + aTable); - int count = 0; + int count = 0; while (resultSet.next()) { count++; } + return count; } + /** + * DOCUMENT ME! + * + * @param aResultSet DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws SQLException DOCUMENT ME! + */ public int countResultSet(ResultSet aResultSet) throws SQLException { int count = 0; @@ -517,5 +586,4 @@ public class DatabaseTesterComponent { return count; } - } diff --git a/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java b/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java index 856b0519..8f500d38 100644 --- a/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java +++ b/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java @@ -1,30 +1,55 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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 { +import java.util.Map; + - public EclipselinkJpaCustomizer() { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class EclipselinkJpaCustomizer implements JpaCustomizer { +/** + * Creates a new EclipselinkJpaCustomizer object. + */ + public EclipselinkJpaCustomizer() { // Empty } - + + /** + * DOCUMENT ME! + * + * @param aPersistenceUnit DOCUMENT ME! + * @param aJpaProperties DOCUMENT ME! + */ @Override - public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + public void customize(PersistenceUnitDescription aPersistenceUnit, + Map aJpaProperties) { // Hack to make JNDI lookup of the datasource work with toplink - aJpaProperties.put("eclipselink.session.customizer", JndiSessionCustomizer.class - .getName()); - + aJpaProperties.put("eclipselink.session.customizer", + JndiSessionCustomizer.class.getName()); + // DDL generation for toplink - aJpaProperties.put("eclipselink.ddl-generation", "create-tables"); + aJpaProperties.put("eclipselink.ddl-generation", "create-tables"); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public ITableFilterSimple getJpaTables() { return new EclipselinkTables(); } - } diff --git a/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java b/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java index d4df0ddd..5bff84c6 100644 --- a/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java +++ b/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java @@ -1,20 +1,37 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.support.persistence.eclipselink; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + import java.util.Arrays; import java.util.List; -import org.dbunit.dataset.DataSetException; -import org.dbunit.dataset.filter.ITableFilterSimple; /** - * Toplink-specific tables. + * Toplink-specific tables. */ public class EclipselinkTables implements ITableFilterSimple { + /** + * DOCUMENT ME! + */ + private static final List TABLES = Arrays.asList(new String[] { + "SEQUENCE" + }); - private static final List TABLES = Arrays.asList(new String[] { "SEQUENCE" } ); - - public boolean accept(String aTableName) throws DataSetException { - return TABLES.contains(aTableName); - } - + /** + * DOCUMENT ME! + * + * @param aTableName DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws DataSetException DOCUMENT ME! + */ + public boolean accept(String aTableName) throws DataSetException { + return TABLES.contains(aTableName); + } } diff --git a/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java b/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java index 9b856f05..d22f326d 100644 --- a/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java +++ b/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java @@ -1,59 +1,75 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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; - + +import javax.naming.Context; +import javax.naming.InitialContext; + + /** - * 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. + * 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"); - } +public class JndiSessionCustomizer implements SessionCustomizer { +/** + * Creates a new JndiSessionCustomizer object. + */ + public JndiSessionCustomizer() { + // Empty. } - catch(Exception e) { - e.printStackTrace(); + + /** + * Get a dataSource connection and set it on the session with + * lookupType=STRING_LOOKUP + * + * @param session DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ + 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/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java b/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java index 870e20a2..1695bc88 100644 --- a/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java +++ b/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java @@ -1,23 +1,38 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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; +import org.wamblee.support.persistence.PersistenceUnitDescription; + +import javax.persistence.EntityManager; + +import javax.sql.DataSource; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DatabaseUtilsTest extends DatabaseUtilsTestBase { - // Empty, all tests inherited + // Empty, all tests inherited } diff --git a/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java b/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java index 84c3fff5..53c8fbf6 100644 --- a/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java +++ b/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java @@ -1,28 +1,36 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.support.persistence.eclipselink; -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import javax.sql.DataSource; +import static junit.framework.Assert.*; 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.JpaBuilder.JpaUnitOfWork; import org.wamblee.support.persistence.JpaTester; import org.wamblee.support.persistence.MyEntityExampleTestBase; -import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; -import static junit.framework.Assert.*; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +import javax.sql.DataSource; /** - * This class shows an example of how to test an entity using jpa. + * 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/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java b/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java index 088202c3..44a9faf5 100644 --- a/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java +++ b/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java @@ -1,32 +1,59 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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 CAPABILIITIES = - Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY, "DERBY"); +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class DerbyDatabaseProvider extends AbstractDatabaseProvider { + /** + * Capabilities of this type of database. + */ + public static final List CAPABILIITIES = Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY, + "DERBY"); - public DerbyDatabaseProvider() { - // Empty - } +/** + * Creates a new DerbyDatabaseProvider object. + */ + public DerbyDatabaseProvider() { + // Empty + } - public Database create() { - return new DerbyDatabase(); - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + 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"); - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + public DatabaseDescription getDescription() { + return new DatabaseDescription(CAPABILIITIES.toArray(new String[0]), + "Derby", "In-memory, volatile, set breakpoint to debug"); + } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override protected List getCapabilities() { - return CAPABILIITIES; + return CAPABILIITIES; } } diff --git a/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java b/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java index fa4def8f..4dd71360 100644 --- a/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java +++ b/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java @@ -1,31 +1,57 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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 { +import java.util.Map; + - public HibernateJpaCustomizer() { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class HibernateJpaCustomizer implements JpaCustomizer { +/** + * Creates a new HibernateJpaCustomizer object. + */ + public HibernateJpaCustomizer() { // Empty } - + + /** + * DOCUMENT ME! + * + * @param aPersistenceUnit DOCUMENT ME! + * @param aJpaProperties DOCUMENT ME! + */ @Override - public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + public void customize(PersistenceUnitDescription aPersistenceUnit, + Map 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()); - + aJpaProperties.put("javax.persistence.nonJtaDataSource", + aPersistenceUnit.getJndiName()); + // Hibernate schema generation - aJpaProperties.put("hibernate.hbm2ddl.auto", "create"); + aJpaProperties.put("hibernate.hbm2ddl.auto", "create"); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public ITableFilterSimple getJpaTables() { return new HibernateTables(); } - } diff --git a/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java b/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java index 4b2c8a09..c0a8c7c8 100644 --- a/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java +++ b/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java @@ -1,20 +1,35 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.support.persistence.hibernate; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + import java.util.Arrays; import java.util.List; -import org.dbunit.dataset.DataSetException; -import org.dbunit.dataset.filter.ITableFilterSimple; /** - * Toplink-specific tables. + * Toplink-specific tables. */ public class HibernateTables implements ITableFilterSimple { + /** + * DOCUMENT ME! + */ + private static final List TABLES = Arrays.asList(new String[] { "" }); - private static final List TABLES = Arrays.asList(new String[] { "" } ); - - public boolean accept(String aTableName) throws DataSetException { - return TABLES.contains(aTableName); - } - + /** + * DOCUMENT ME! + * + * @param aTableName DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws DataSetException DOCUMENT ME! + */ + public boolean accept(String aTableName) throws DataSetException { + return TABLES.contains(aTableName); + } } diff --git a/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java b/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java index 68edf22a..d581b8e0 100644 --- a/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java +++ b/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java @@ -1,23 +1,38 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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; +import org.wamblee.support.persistence.PersistenceUnitDescription; + +import javax.persistence.EntityManager; + +import javax.sql.DataSource; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DatabaseUtilsTest extends DatabaseUtilsTestBase { - // Empty, all tests inherited + // Empty, all tests inherited } diff --git a/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java b/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java index 537cb549..ec5f0059 100644 --- a/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java +++ b/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java @@ -1,28 +1,36 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.support.persistence.hibernate; -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import javax.sql.DataSource; +import static junit.framework.Assert.*; 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.JpaBuilder.JpaUnitOfWork; import org.wamblee.support.persistence.JpaTester; import org.wamblee.support.persistence.MyEntityExampleTestBase; -import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; -import static junit.framework.Assert.*; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +import javax.sql.DataSource; /** - * This class shows an example of how to test an entity using jpa. + * 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/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java b/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java index 814fe593..dbaeccab 100644 --- a/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java +++ b/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java @@ -1,59 +1,75 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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; - + +import javax.naming.Context; +import javax.naming.InitialContext; + + /** - * 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. + * 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"); - } +public class JndiSessionCustomizer implements SessionCustomizer { +/** + * Creates a new JndiSessionCustomizer object. + */ + public JndiSessionCustomizer() { + // Empty. } - catch(Exception e) { - e.printStackTrace(); + + /** + * Get a dataSource connection and set it on the session with + * lookupType=STRING_LOOKUP + * + * @param session DOCUMENT ME! + * + * @throws Exception DOCUMENT ME! + */ + 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/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java b/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java index 5ba15e84..4eeca2db 100644 --- a/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java +++ b/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java @@ -1,30 +1,55 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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 { +import java.util.Map; + - public ToplinkJpaCustomizer() { +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ +public class ToplinkJpaCustomizer implements JpaCustomizer { +/** + * Creates a new ToplinkJpaCustomizer object. + */ + public ToplinkJpaCustomizer() { // Empty } - + + /** + * DOCUMENT ME! + * + * @param aPersistenceUnit DOCUMENT ME! + * @param aJpaProperties DOCUMENT ME! + */ @Override - public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + public void customize(PersistenceUnitDescription aPersistenceUnit, + Map aJpaProperties) { // Hack to make JNDI lookup of the datasource work with toplink - aJpaProperties.put("toplink.session.customizer", JndiSessionCustomizer.class - .getName()); - + aJpaProperties.put("toplink.session.customizer", + JndiSessionCustomizer.class.getName()); + // DDL generation for toplink - aJpaProperties.put("toplink.ddl-generation", "create-tables"); + aJpaProperties.put("toplink.ddl-generation", "create-tables"); } - + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ @Override public ITableFilterSimple getJpaTables() { return new ToplinkTables(); } - } diff --git a/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java b/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java index cd3a0562..f34c2102 100644 --- a/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java +++ b/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java @@ -1,20 +1,37 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.support.persistence.toplink; +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + import java.util.Arrays; import java.util.List; -import org.dbunit.dataset.DataSetException; -import org.dbunit.dataset.filter.ITableFilterSimple; /** - * Toplink-specific tables. + * Toplink-specific tables. */ public class ToplinkTables implements ITableFilterSimple { + /** + * DOCUMENT ME! + */ + private static final List TABLES = Arrays.asList(new String[] { + "SEQUENCE" + }); - private static final List TABLES = Arrays.asList(new String[] { "SEQUENCE" } ); - - public boolean accept(String aTableName) throws DataSetException { - return TABLES.contains(aTableName); - } - + /** + * DOCUMENT ME! + * + * @param aTableName DOCUMENT ME! + * + * @return DOCUMENT ME! + * + * @throws DataSetException DOCUMENT ME! + */ + public boolean accept(String aTableName) throws DataSetException { + return TABLES.contains(aTableName); + } } diff --git a/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java b/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java index 095109d3..a2bf5345 100644 --- a/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java +++ b/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java @@ -1,23 +1,38 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ 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; +import org.wamblee.support.persistence.PersistenceUnitDescription; + +import javax.persistence.EntityManager; + +import javax.sql.DataSource; + +/** + * DOCUMENT ME! + * + * @author $author$ + * @version $Revision$ + */ public class DatabaseUtilsTest extends DatabaseUtilsTestBase { - // Empty, all tests inherited + // Empty, all tests inherited } diff --git a/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java b/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java index 415ee70f..55b84c48 100644 --- a/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java +++ b/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java @@ -1,28 +1,36 @@ +/* + * SCJD assignment, URLyBird, Erik Brakkee. + * Candidate ID: sr1399267. + */ package org.wamblee.support.persistence.toplink; -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import javax.sql.DataSource; +import static junit.framework.Assert.*; 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.JpaBuilder.JpaUnitOfWork; import org.wamblee.support.persistence.JpaTester; import org.wamblee.support.persistence.MyEntityExampleTestBase; -import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; -import static junit.framework.Assert.*; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +import javax.sql.DataSource; /** - * This class shows an example of how to test an entity using jpa. + * This class shows an example of how to test an entity using jpa. */ public class MyEntityExampleTest extends MyEntityExampleTestBase { // Empty, all tests are inherited -- 2.31.1