From: erik Date: Tue, 13 Apr 2010 19:03:24 +0000 (+0000) Subject: [maven-release-plugin] copy for tag wamblee-utils-0.2 X-Git-Tag: wamblee-utils-0.2.2@623~8 X-Git-Url: http://wamblee.org/gitweb/?a=commitdiff_plain;h=7372c53837fd00668f0b7dad1259ed3defddcfbe;p=utils [maven-release-plugin] copy for tag wamblee-utils-0.2 --- diff --git a/tags/wamblee-utils-0.2/ABOUT.txt b/tags/wamblee-utils-0.2/ABOUT.txt new file mode 100644 index 00000000..8d0afc91 --- /dev/null +++ b/tags/wamblee-utils-0.2/ABOUT.txt @@ -0,0 +1,4 @@ +This is the utilities project of wamblee.org. It contains various utilities +and useful programs for various purposes. The most important part is the +support library. + diff --git a/tags/wamblee-utils-0.2/LICENSE b/tags/wamblee-utils-0.2/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/tags/wamblee-utils-0.2/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tags/wamblee-utils-0.2/README.txt b/tags/wamblee-utils-0.2/README.txt new file mode 100644 index 00000000..a41ba437 --- /dev/null +++ b/tags/wamblee-utils-0.2/README.txt @@ -0,0 +1,37 @@ +Support utilities for enterprise development +============================================ + +* support: Base (non-Java EE) support +* system: An IOC framework experiment. This should be flexible enough as a basis for + a CDI implementation. It currently offers only a programmatic API and does not use + annotations. +* hibernate-jpa: Hibernate JPA dependencies +* security: Security support utlities (user management and authorization) +* test: Test support for JEE testing. In particular, junit testing with an inmemory or + external database and support for JPA testing with several JPA providers. + + +To be removed from this project (currently skipped from the release) +==================================================================== + +* socketproxy: An old socketproxy. To be removed from the utilities +* mythtv: An application for exposing mythtv recordings in a useful directory structure + This will be removed from the utilities + +To be added to this project +=========================== +* utilities for CDI +* wicket utilities. + +Building +======== + +You need maven2 and java 6 + +Releasing +========= + +Trigger release settings by building with -Dwamblee.release=true +This will skip some projects that are not to be released. + + diff --git a/tags/wamblee-utils-0.2/TODO.txt b/tags/wamblee-utils-0.2/TODO.txt new file mode 100644 index 00000000..6efaa913 --- /dev/null +++ b/tags/wamblee-utils-0.2/TODO.txt @@ -0,0 +1,12 @@ + +* refactor: Create jpa subproject with separate subprojects for api, hibernate, + toplink-essentials and eclipselink + Each subproject contains the required repo settings +* Maven profile for nonrelease which is dactivated when release is active. +* Have toplink, eclipselink, hibernate profiles that are deactivated by + release and active by default. + +* add cdi subproject to the utils +* add schemagen for user management part. +* JPA 2.0 implementation for security. + diff --git a/tags/wamblee-utils-0.2/build/checkstyle-noframes.xsl b/tags/wamblee-utils-0.2/build/checkstyle-noframes.xsl new file mode 100644 index 00000000..5f18134b --- /dev/null +++ b/tags/wamblee-utils-0.2/build/checkstyle-noframes.xsl @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

CheckStyle Audit

Designed for use with CheckStyle and Ant.
+
+ + + +
+ + + +
+ + + + + +

+

+ +


+ + + + +
+ + + + +

Files

+ + + + + + + + + + + + + + +
NameErrors
+
+ + + + +

File

+ + + + + + + + + + + + + +
Error DescriptionLine
+ Back to top +
+ + + +

Summary

+ + + + + + + + + + + + +
FilesErrors
+
+ + + + a + b + + +
+ + diff --git a/tags/wamblee-utils-0.2/build/checkstyle-simple.xsl b/tags/wamblee-utils-0.2/build/checkstyle-simple.xsl new file mode 100644 index 00000000..d98cbcbe --- /dev/null +++ b/tags/wamblee-utils-0.2/build/checkstyle-simple.xsl @@ -0,0 +1,71 @@ + + + + + + + + Sun Coding Style Violations + + +

Coding Style Check Results

+ + + + + + + + + + + + + + + + + + + + +
Summary
Total files checked
Files with errors
Total errors
Errors per file
+
+

The following are violations of the Sun Coding-Style Standards:

+

+ + + + + + + + + + + +
File: + +
+ + + + + + +
Line Number Error Message
+

+ + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/build/style.xml b/tags/wamblee-utils-0.2/build/style.xml new file mode 100644 index 00000000..58b854ea --- /dev/null +++ b/tags/wamblee-utils-0.2/build/style.xml @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/hibernate-jpa/pom.xml b/tags/wamblee-utils-0.2/hibernate-jpa/pom.xml new file mode 100644 index 00000000..18a43a00 --- /dev/null +++ b/tags/wamblee-utils-0.2/hibernate-jpa/pom.xml @@ -0,0 +1,46 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-hibernate-jpa + jar + /hibernate-jpa + http://wamblee.org + + + + javax.transaction + transaction-api + 1.1 + test + + + org.hibernate + hibernate-entitymanager + 3.4.0.GA + + + javax.transaction + jta + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/pom.xml b/tags/wamblee-utils-0.2/pom.xml new file mode 100644 index 00000000..8a80684c --- /dev/null +++ b/tags/wamblee-utils-0.2/pom.xml @@ -0,0 +1,565 @@ + + 4.0.0 + org.wamblee + wamblee-utils + pom + 0.2 + / + wamblee.org utilities library + http://wamblee.org + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + https://wamblee.org/viewvc/utils/tags/wamblee-utils-0.2 + scm:svn:https://wamblee.org/svn/public/utils/tags/wamblee-utils-0.2 + + + + support + system + hibernate-jpa + security + test + + + + junit + junit + test + + + org.dbunit + dbunit + test + + + org.apache.derby + derby + test + + + org.apache.derby + derbyclient + test + + + org.apache.derby + derbynet + test + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-jdk14 + test + + + + mysql + mysql-connector-java + test + + + org.mockito + mockito-all + 1.8.0 + test + + + + + + + + + + oro + oro + 2.0.6 + + + + + javax.transaction + transaction-api + 1.1 + + + + junit + junit + 4.4 + + + org.dbunit + dbunit + 2.4.7 + + + org.slf4j + slf4j-api + 1.5.11 + + + org.slf4j + slf4j-jdk14 + 1.5.11 + + + + javax.persistence + persistence-api + 1.0 + provided + + + javax.activation + activation + 1.1 + + + javax.mail + mail + 1.4.1 + + + javax.servlet + servlet-api + 2.3 + jar + provided + + + mysql + mysql-connector-java + 5.1.12 + + + org.apache.derby + derby + 10.5.3.0_1 + + + org.apache.derby + derbyclient + 10.5.3.0_1 + + + org.apache.derby + derbynet + 10.5.3.0_1 + + + quartz + quartz + 1.5.1 + + + jtidy + jtidy + 4aug2000r7-dev + + + + + commons-logging + commons-logging + 1.0.2 + + + commons-httpclient + commons-httpclient + 3.0 + + + commons-beanutils + commons-beanutils + 1.7.0 + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-jms + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-hibernate3 + ${spring.version} + + + org.springframework + spring-jpa + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + + + log4j + log4j + 1.2.8 + + + dom4j + dom4j + 1.6 + + + xml-apis + xml-apis + + + + + net.sf.ehcache + ehcache + 1.2.3 + + + + commons-email + commons-email + 1.0 + + + jaxen + jaxen + 1.1-beta-9 + + + xom + xom + + + xerces + xmlParserAPIs + + + + + jstl + jstl + 1.1.2 + + + taglibs + standard + 1.1.2 + + + jfree + jfreechart + 1.0.1 + + + jfree + jcommon + 1.0.2 + + + + javax + javaee-api + 6.0 + provided + + + + commons-codec + commons-codec + 1.3 + + + + commons-dbcp + commons-dbcp + 1.4 + + + toplink.essentials + toplink-essentials + 2.0-36 + + + org.eclipse.persistence + eclipselink + 2.0.0 + compile + + + + + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.0 + + true + javadoc:jar deploy + + + + maven-clean-plugin + 2.4 + + + + . + + derby.log + createDDL.jdbc + dropDDL.jdbc + + + **/important.log + **/another-important.log + + false + + + + + + + org.codehaus.mojo + jalopy-maven-plugin + + UNIX + org.wamblee.jalopy.xml + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + + true + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + org.codehaus.mojo + cobertura-maven-plugin + + + + clean + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + + + + checkstyle + javadoc + dependencies + project-team + mailing-list + issue-tracking + license + scm + + + + + + org.codehaus.mojo + changes-maven-plugin + 2.0-beta-1 + + + + changes-report + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.codehaus.mojo + surefire-report-maven-plugin + + + + org.codehaus.mojo + cobertura-maven-plugin + + + xml + html + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + config/sun_checks.xml + + + + + + org.codehaus.mojo + taglist-maven-plugin + + + TODO + @todo + FIXME + + + + + + + + + + release + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + + sonatype-nexus-staging + Nexus Release Repository + http://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + all + + + !performRelease + + + + + local + Local directory + file:${user.home}/java/workspace/deploy + + + + + + + + 2.0.8 + 2.4.0 + + + diff --git a/tags/wamblee-utils-0.2/release.sh b/tags/wamblee-utils-0.2/release.sh new file mode 100755 index 00000000..68483a09 --- /dev/null +++ b/tags/wamblee-utils-0.2/release.sh @@ -0,0 +1,3 @@ + +mvn release:prepare +mvn -DperformRelease=true release:perform -Darguments="-Dgpg.passphrase=xxx" diff --git a/tags/wamblee-utils-0.2/security/pom.xml b/tags/wamblee-utils-0.2/security/pom.xml new file mode 100644 index 00000000..44711056 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/pom.xml @@ -0,0 +1,101 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-security + jar + /security + http://wamblee.org + + + + org.wamblee + wamblee-support-general + 0.2 + + + org.wamblee + wamblee-support-general + test-jar + 0.2 + + + org.wamblee + wamblee-test-enterprise + 0.2 + test + + + org.wamblee + wamblee-system-spring + 0.2 + + + org.wamblee + wamblee-system-spring + test-jar + 0.2 + + + org.wamblee + wamblee-system-general + test-jar + 0.2 + + + org.wamblee + wamblee-support-spring + 0.2 + + + org.wamblee + wamblee-support-spring + test-jar + 0.2 + + + + org.wamblee + wamblee-hibernate-jpa + 0.2 + + + + commons-codec + commons-codec + + + + org.springframework + spring-beans + + + org.springframework + spring-hibernate3 + + + org.hibernate + hibernate + + + + + org.springframework + spring-aop + + + javax.transaction + transaction-api + 1.1 + test + + + + + diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AllOperation.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AllOperation.java new file mode 100644 index 00000000..c76d00ca --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AllOperation.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * An superclass of all other operations. + */ +public class AllOperation implements Operation { + + private static final String OPERATION = "all"; + + /** + * Operation name. + */ + private String _name; + + /** + * Constructs an all operation. + * + */ + public AllOperation() { + _name = OPERATION; + } + + /** + * Constructs the operation, this constructor is the one that must be used + * by subclasses. + * @param aName Name of the operation. This name must be unique among all operations. + */ + protected AllOperation(String aName) { + _name = aName; + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.Operation#getName() + */ + public String getName() { + return _name; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java new file mode 100644 index 00000000..fdee026e --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AnyUserCondition.java @@ -0,0 +1,52 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.AbstractPersistent; +import org.wamblee.usermgt.User; + +/** + * Matches any user. + * + * @author Erik Brakkee + */ +public class AnyUserCondition extends AbstractPersistent implements UserCondition { + + /** + * Constructs the condition. + * + */ + public AnyUserCondition() { + // Empty. + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.User) + */ + public boolean matches(User aUser) { + return true; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AnyUserCondition()"; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java new file mode 100644 index 00000000..d7a81fd5 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationException.java @@ -0,0 +1,44 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Authorization exception to be thrown when + * a resouce may not be accessed. + * + * @author Erik Brakkee + */ +public class AuthorizationException extends RuntimeException { + + private Object _resource; + private Operation _operation; + + public AuthorizationException(Object aResource, Operation aOperation) { + super("Operation '" + aOperation + "' not allowed on '" + aResource + "'"); + _resource = aResource; + _operation = aOperation; + } + + public Object getResource() { + return _resource; + } + + public Operation getOperation() { + return _operation; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java new file mode 100644 index 00000000..7423eab9 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationInitializer.java @@ -0,0 +1,43 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.apache.log4j.Logger; + + +/** + * Inititializer class for authorization rules. This class initializes the + * authorization rules in case none are present. + */ +public class AuthorizationInitializer { + + private static final Logger LOGGER = Logger.getLogger(AuthorizationInitializer.class); + + /** + * Initializes authorization rules in case none are present. + * @param aService Authorization service. + * @param aRules Default rules for initialization. + */ + public AuthorizationInitializer(AuthorizationService aService, AuthorizationRule[] aRules) { + if ( aService.getRules().length == 0 ) { + for (AuthorizationRule rule: aRules) { + LOGGER.info("Appending authorization rule " + rule); + aService.appendRule(rule); + } + } + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java new file mode 100644 index 00000000..a394910f --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationResult.java @@ -0,0 +1,44 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Represents the result of an authorization decision. + * + * @author Erik Brakkee + */ +public enum AuthorizationResult { + /** + * Access is granted. + */ + GRANTED, + + /** + * Access is denied. + */ + DENIED, + + /** + * Access is undecided. + */ + UNDECIDED, + + /** + * Unsupported resource. + */ + UNSUPPORTED_RESOURCE +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java new file mode 100644 index 00000000..575f4f21 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationRule.java @@ -0,0 +1,46 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.Persistent; +import org.wamblee.usermgt.User; + +/** + * Represents an authorization rule to determine whether an operation is allowed on a resource. + * + * @author Erik Brakkee + */ +public interface AuthorizationRule extends Persistent { + + /** + * Returns the supported object types for which this authorization rule applies. + * This can be used by the authorization service for optimization. + * @return Array of supported types. + */ + Class[] getSupportedTypes(); + + /** + * Determines whether an operation is allowed on a certain resource. + * The rule implementation must be prepared to deal with resources for which it does + * not apply. In those cases it should return {@link AuthorizationResult#UNSUPPORTED_RESOURCE}. + * @param aResource Resource. + * @param anOperation Operation. + * @param aUser Current user. + * @return Authorization result. + */ + AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java new file mode 100644 index 00000000..01150622 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/AuthorizationService.java @@ -0,0 +1,69 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.Persistent; + +/** + * Service to determine if access to a certain resource is allowed. + * + * @author Erik Brakkee + */ +public interface AuthorizationService extends Persistent { + + /** + * Checks whether an operation is allowed on a resource. + * @param aResource Resource. + * @param aOperation Operation. + * @return Checks whether the operation is allowed on a resource. + */ + boolean isAllowed(Object aResource, Operation aOperation); + + /** + * Same as {@link #isAllowed(Object, Operation)} but throws a + * RuntimeException in case access is not allowed. + * @param aResource Resource to check. + * @param aOperation Operation to perform. + * @return Resource that was checked. + */ + T check(T aResource, Operation aOperation); + + /** + * Gets the authorization rules. + * @return Rules. + */ + AuthorizationRule[] getRules(); + + /** + * Appends a new authorization rule to the end. + * @param aRule Rule to append. + */ + void appendRule(AuthorizationRule aRule); + + /** + * Removes a rule. + * @param aRule Index of the rule to remove. + */ + void removeRule(int aIndex); + + /** + * Inserts a rule. + * @param aIndex Index of the position of the rule after insertion. + * @param aRule Rule to insert. + */ + void insertRuleAfter(int aIndex, AuthorizationRule aRule); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java new file mode 100644 index 00000000..b9a96d8e --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/CreateOperation.java @@ -0,0 +1,36 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Represents an operation to create something. + * + * @author Erik Brakkee + */ +public class CreateOperation extends AllOperation { + + private static final String OPERATION = "create"; + + /** + * Constructs the operation. + * + */ + public CreateOperation() { + super(OPERATION); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java new file mode 100644 index 00000000..b3dc524d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DefaultAuthorizationService.java @@ -0,0 +1,155 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.persistence.AbstractPersistent; +import org.wamblee.usermgt.User; +import org.wamblee.usermgt.UserAccessor; + +/** + * Default implementation of an authorization service. + * To determine whether access to a resource is allowed, the service consults a number + * of authorization rules in a fixed order. The first rule that gives a result GRANTED or + * DENIED determines the result of the evaluation. Rules that return any other result are + * ignoed. If none of the rules match, than access is denied. + * + * @author Erik Brakkee + */ +public class DefaultAuthorizationService extends AbstractPersistent implements AuthorizationService { + + /** + * List of ordered authorization rules. + */ + private List _rules; + + /** + * User accessor used to obtain the current user. + */ + private UserAccessor _userAccessor; + + /** + * Name for this instance of the authorization service. + */ + private String _name; + + /** + * Constructs the service. + * @param aAccessor User accessor. + * @param aName Name of this instance of the service. + */ + public DefaultAuthorizationService(UserAccessor aAccessor, String aName) { + _rules = new ArrayList(); + _userAccessor = aAccessor; + _name = aName; + } + + /** + * Constructs the authorization service. + */ + public DefaultAuthorizationService() { + _rules = new ArrayList(); + _userAccessor = null; + _name = null; + } + + /** + * Sets the user accessor. + * @param aUserAccessor User accessor. + */ + public void setUserAccessor(UserAccessor aUserAccessor) { + _userAccessor = aUserAccessor; + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation) + */ + public boolean isAllowed(Object aResource, Operation aOperation) { + User user = _userAccessor.getCurrentUser(); + for (AuthorizationRule rule: _rules) { + switch ( rule.isAllowed(aResource, aOperation, user)) { + case DENIED: { return false; } + case GRANTED: { return true; } + } + } + return false; + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation) + */ + public T check(T aResource, Operation aOperation) { + if ( !isAllowed(aResource, aOperation)) { + throw new AuthorizationException(aResource, aOperation); + } + return aResource; + } + + protected String getName() { + return _name; + } + + public void setName(String aName) { + _name = aName; + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#getRules() + */ + public AuthorizationRule[] getRules() { + return _rules.toArray(new AuthorizationRule[0]); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule) + */ + public void appendRule(AuthorizationRule aRule) { + _rules.add(aRule); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, org.wamblee.security.authorization.AuthorizationRule) + */ + public void insertRuleAfter(int aIndex, AuthorizationRule aRule) { + _rules.add(aIndex, aRule); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int) + */ + public void removeRule(int aIndex) { + _rules.remove(aIndex); + } + + /** + * For OR mapping. + * @return The rules. + */ + protected List getMappedRules() { + return _rules; + } + + /** + * For OR mapping. + * @param aRules The rules. + */ + protected void setMappedRules(List aRules) { + _rules = aRules; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java new file mode 100644 index 00000000..0a240923 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DefaultOperationRegistry.java @@ -0,0 +1,88 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import java.util.ArrayList; +import java.util.Map; +import java.util.TreeMap; + +/** + * Operation registry implementation. + * This implementation ignores the distinction between different types of resources + * and simply assumes that every operation is applicable to every type of resource. + * + * @author Erik Brakkee + */ +public class DefaultOperationRegistry implements OperationRegistry { + + private Map _operations; + + public DefaultOperationRegistry(Operation[] aOperations) { + _operations = new TreeMap(); + for (Operation operation: aOperations) { + _operations.put(operation.getName(), operation); + } + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.OperationRegistry#getOperations(java.lang.Class) + */ + public Operation[] getOperations(Class aResourceClass) { + return _operations.values().toArray(new Operation[0]); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.OperationRegistry#encode(org.wamblee.security.authorization.Operation[]) + */ + public String encode(Operation[] aOperations) { + StringBuffer buffer = new StringBuffer(); + for (Operation operation: aOperations) { + if ( buffer.length() > 0 ) { + buffer.append(','); + } + buffer.append(operation.getName()); + } + return buffer.toString(); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.Class, java.lang.String) + */ + public Operation[] decode(Class aResourceClass, String aOperationsString) { + return decode(aOperationsString); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.OperationRegistry#decode(java.lang.String) + */ + public Operation[] decode(String aOperationsString) { + if ( aOperationsString.length() == 0 ) { + return new Operation[0]; + } + String[] names = aOperationsString.split(","); + ArrayList result = new ArrayList(); + for (String name: names) { + Operation operation = _operations.get(name); + if ( operation == null ) { + throw new IllegalArgumentException("Unknown operation '" + name + "'"); + } + result.add(operation); + } + return result.toArray(new Operation[0]); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java new file mode 100644 index 00000000..7bdaac51 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/DeleteOperation.java @@ -0,0 +1,35 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Deletes the operation. + * + * @author Erik Brakkee + */ +public class DeleteOperation extends AllOperation { + + private static final String OPERATION = "delete"; + + /** + * Constructs the operation. + * + */ + public DeleteOperation() { + super(OPERATION); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java new file mode 100644 index 00000000..8949fc76 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/GroupUserCondition.java @@ -0,0 +1,79 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.AbstractPersistent; +import org.wamblee.usermgt.User; + +/** + * Checks if a user against a specific group. + * + * @author Erik Brakkee + */ +public class GroupUserCondition extends AbstractPersistent implements UserCondition { + + /** + * Group the user must be in. + */ + private String _group; + + /** + * Constructs the condition. + * @param aGroup Group the user must be in. + */ + public GroupUserCondition(String aGroup) { + _group = aGroup; + } + + /** + * For OR mapping. + * + */ + protected GroupUserCondition() { + _group = null; + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.UserCondition#matches(org.wamblee.usermgt.UserAccessor) + */ + public boolean matches(User aUser) { + return aUser.isInGroup(_group); + } + + /** + * @return Returns the _group. + */ + protected String getGroup() { + return _group; + } + + /** + * @param _group The _group to set. + */ + protected void setGroup(String aGroup) { + _group = aGroup; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "GroupUserCondition(group=" + _group + ")"; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java new file mode 100644 index 00000000..e5a4d686 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/IsaOperationCondition.java @@ -0,0 +1,98 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.AbstractPersistent; + +/** + * Determiens if an operation is a subclass of a specified operation. + */ +public class IsaOperationCondition extends AbstractPersistent implements + OperationCondition { + + /** + * Operation that the other operation must be a subclass of. + */ + private Class _operation; + + /** + * Constructs the condition. + * + * @param aOperation + * Operation that an operation must be an instance of. + */ + public IsaOperationCondition(Class aOperation) { + _operation = aOperation; + } + + /** + * For OR mapping. + * + */ + public IsaOperationCondition() { + _operation = null; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.OperationCondition#matches(org.wamblee.security.authorization.Operation) + */ + public boolean matches(Operation aOperation) { + return _operation.isInstance(aOperation); + } + + /** + * Gets the operation as a string. For OR mapping only. + * + * @return Operation string. + */ + protected String getOperationString() { + if (_operation == null) { + return null; + } + return _operation.getName(); + } + + /** + * Sets the operation as a string. For OR mapping only. + * + * @param aOperation + * Operation string. + */ + protected void setOperationString(String aOperation) { + if (aOperation == null ) { + return; + } + try { + _operation = (Class)Class.forName(aOperation); + } catch (Exception e) { + throw new IllegalArgumentException("Unknown class '" + aOperation + "'"); + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "IsaOperationCondition(operation=" + _operation.getName() + ")"; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/Operation.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/Operation.java new file mode 100644 index 00000000..24205065 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/Operation.java @@ -0,0 +1,33 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Represents an operation on a resource. + * An operation should contain no state to be persisted since only the name of the + * operation is persisted. + * + * @author Erik Brakkee + */ +public interface Operation { + + /** + * Gets the name of the operation. + * @return Operation. + */ + String getName(); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java new file mode 100644 index 00000000..db6e0d0a --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/OperationCondition.java @@ -0,0 +1,35 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.Persistent; + +/** + * Checks if an operation matches a condition. + * + * @author Erik Brakkee + */ +public interface OperationCondition extends Persistent { + + + /** + * Determines if the operation matches. + * @param aOperation Operation. + * @return True iff the operation matches. + */ + boolean matches(Operation aOperation); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java new file mode 100644 index 00000000..bcce7c96 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/OperationRegistry.java @@ -0,0 +1,57 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + + +/** + * Utility to map between a list of operations and a string based + * on the names of the operations. + * + * @author Erik Brakkee + */ +public interface OperationRegistry { + + /** + * Gets the supported operations for a given resource class. + * @param aResourceClass Resource class. + * @return Supported operations for that class. + */ + Operation[] getOperations(Class aResourceClass); + + /** + * Converts a number of operations to a string. + * @param aOperations Operations to convert. + * @return String representation of the allowed operations. + */ + String encode(Operation[] aOperations); + + /** + * Converts an operations string to an array of operations. + * @param aResourceClass Resource class. + * @param aOperationsString Operations string as returned by {@link #encode(Operation[])}. + * @return Operations array. + */ + Operation[] decode(Class aResourceClass, String aOperationsString); + + /** + * Converts an operations string to an array of operations. + * @param aOperationsString Operations string as returned by {@link #encode(Operation[])}. + * @return Operations array. + */ + Operation[] decode(String aOperationsString); + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/PathCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/PathCondition.java new file mode 100644 index 00000000..8c970177 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/PathCondition.java @@ -0,0 +1,34 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.Persistent; + +/** + * Checks if a path satisfies a condition. + * + * @author Erik Brakkee + */ +public interface PathCondition extends Persistent { + + /** + * Checks if the path matches the condition. + * @param aPath Path to match. + * @return True iff the path matches. + */ + boolean matches(String aPath); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java new file mode 100644 index 00000000..839fdb18 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/ReadOperation.java @@ -0,0 +1,35 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Represents a read operation on a resource. + * + * @author Erik Brakkee + */ +public class ReadOperation extends AllOperation { + + private static final String OPERATION = "read"; + + /** + * Constructs the operation. + * + */ + public ReadOperation() { + super(OPERATION); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java new file mode 100644 index 00000000..5c373e84 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/RegexpPathCondition.java @@ -0,0 +1,77 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.AbstractPersistent; + +/** + * Condition to check whether a path matches a given regula expression. + * + * @author Erik Brakkee + */ +public class RegexpPathCondition extends AbstractPersistent implements PathCondition { + + /** + * String the path must start with. + */ + private String _pattern; + + /** + * Constructs the condition. + * @param aPattern String the path must start with. + */ + public RegexpPathCondition(String aPattern) { + _pattern = aPattern; + } + + /** + * For OR mapping. + * + */ + protected RegexpPathCondition() { + _pattern = null; + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.PathCondition#matches(java.lang.String) + */ + public boolean matches(String aPath) { + return aPath.matches(_pattern); + } + + /** + * @return Returns the _path. + */ + protected String getPattern() { + return _pattern; + } + + /** + * @param aPattern The _path to set. + */ + protected void setPattern(String aPattern) { + _pattern = aPattern; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "RegexpCondition(pattern = '" + _pattern + "')"; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java new file mode 100644 index 00000000..59f8627c --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/StartsWithPathCondition.java @@ -0,0 +1,50 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + + +/** + * Condition to check whether a path starts with a given string. + * + * @author Erik Brakkee + */ +public class StartsWithPathCondition extends RegexpPathCondition { + + /** + * Constructs the condition. + * @param aPath String the path must start with. + */ + public StartsWithPathCondition(String aPath) { + super( aPath + ".*"); + } + + /** + * For OR mapping. + * + */ + protected StartsWithPathCondition() { + super(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "StartsWithPathCondition(pattern = '" + getPattern() + "')"; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java new file mode 100644 index 00000000..0d22d1ca --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/UrlAuthorizationRule.java @@ -0,0 +1,264 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import static org.wamblee.security.authorization.AuthorizationResult.DENIED; +import static org.wamblee.security.authorization.AuthorizationResult.GRANTED; +import static org.wamblee.security.authorization.AuthorizationResult.UNDECIDED; +import static org.wamblee.security.authorization.AuthorizationResult.UNSUPPORTED_RESOURCE; + +import org.apache.log4j.Logger; +import org.wamblee.persistence.AbstractPersistent; +import org.wamblee.usermgt.User; + +/** + * Utility base class for implementation of authentication rules based on the + *

    + *
  • 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 { + + private static final Logger LOGGER = Logger.getLogger(UrlAuthorizationRule.class); + + /** + * Result that the rule will return in case there is a match. + */ + private AuthorizationResult _result; + + /** + * A condition which specifies which users the rule is for. + */ + private UserCondition _userCondition; + + /** + * Path the rule applies for. + */ + private PathCondition _pathCondition; + + /** + * Resource class that the rule applies for. + */ + private Class _resourceClass; + + /** + * Operation that this rule is for. + */ + private OperationCondition _operationCondition; + + /** + * Constructs an authorization rule. + * IF the group and path match, then the provided result will be returned. + * @param aResult Result of the authorization when the path and group match. + * @param aUserCondition Condition to match users. + * @param aPathCondition Condition to match paths with. + * @param aResourceClass Supported resource class this is for. + * @param aOperationCondition Condition to match the operation with. + */ + protected UrlAuthorizationRule(AuthorizationResult aResult, UserCondition aUserCondition, + PathCondition aPathCondition, Class aResourceClass, OperationCondition aOperationCondition) { + if ( !aResult.equals(GRANTED) && !aResult.equals(DENIED)) { + throw new IllegalArgumentException("Only GRANTED or DENIED may be used: " + aResult); + } + _result = aResult; + _userCondition = aUserCondition; + _pathCondition = aPathCondition; + _resourceClass = aResourceClass; + _operationCondition = aOperationCondition; + } + + /** + * For OR mapping. + * + */ + protected UrlAuthorizationRule(Class aResourceClass) { + _result = null; + _userCondition = null; + _pathCondition = null; + _resourceClass = aResourceClass; + _operationCondition = null; + } + + /** + * For OR mapping. + * + */ + protected UrlAuthorizationRule() { + _result = null; + _userCondition = null; + _pathCondition = null; + _resourceClass = null; + _operationCondition = null; + } + + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationRule#getSupportedTypes() + */ + public Class[] getSupportedTypes() { + return new Class[] { _resourceClass }; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationRule#isAllowed(java.lang.Object, + * org.wamblee.security.authorization.Operation) + */ + public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) { + if ( ! _resourceClass.isInstance(aResource)) { + return UNSUPPORTED_RESOURCE; + } + String path = getResourcePath(aResource); + return isAllowed(path, anOperation, aUser); + } + + /** + * Determines if the operation is allowed on the resource. + * @param aPath Path of the resource. + * @param aOperation Operation to be done. + * @param aUser Currently logged in user or null if no user is logged in. + * @return Authorization result, + */ + protected AuthorizationResult isAllowed(String aPath, Operation aOperation, User aUser) { + if ( ! _pathCondition.matches(aPath) ) { + return UNDECIDED; + } + if ( !_operationCondition.matches(aOperation) ) { + return UNDECIDED; + } + if ( !_userCondition.matches(aUser)) { + return UNDECIDED; + } + return _result; + } + + /** + * Gets the path of the resource. + * @param aResource Resource, guaranteed to be an instance of + * {@link #_resourceClass}. + * @return Path of the resource. + */ + protected abstract String getResourcePath(Object aResource); + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "UrlAUthorizationRule(result = " + _result + + ", pathCondition = " + _pathCondition + + ", userCondition = " + _userCondition + + ", resourceClass = " + _resourceClass + ")"; + } + + /** + * Gets the authorization result for OR mapping. + * @return Result. + */ + protected String getAuthorizationResultString() { + if ( _result == null ) { + return null; + } + return _result.toString(); + } + + /** + * Sets the authorization result, for OR mapping. + * @param aResult Result. + */ + protected void setAuthorizationResultString(String aResult) { + _result = AuthorizationResult.valueOf(aResult); + } + + protected String getResourceClassName() { + if ( _resourceClass == null ) { + return ""; + } + return _resourceClass.getName(); + } + + protected void setResourceClassName(String aResourceClass) { + try { + _resourceClass = Class.forName(aResourceClass); + } catch (ClassNotFoundException e) { + LOGGER.error("Cannot find resource class '" + aResourceClass + "'", e); + throw new IllegalArgumentException(e.getMessage(), e); + } + } + + /** + * @return Returns the _operationCondition. + */ + public OperationCondition getOperationCondition() { + return _operationCondition; + } + + /** + * @param aOperationCondition The _operationCondition to set. + */ + protected void setOperationCondition(OperationCondition aOperationCondition) { + _operationCondition = aOperationCondition; + } + + /** + * @return Returns the _pathCondition. + */ + public PathCondition getPathCondition() { + return _pathCondition; + } + + /** + * @param aPathCondition The _pathCondition to set. + */ + protected void setPathCondition(PathCondition aPathCondition) { + _pathCondition = aPathCondition; + } + + /** + * @return Returns the _userCondition. + */ + public UserCondition getUserCondition() { + return _userCondition; + } + + /** + * @param aUserCondition The _userCondition to set. + */ + protected void setUserCondition(UserCondition aUserCondition) { + _userCondition = aUserCondition; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/UserCondition.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/UserCondition.java new file mode 100644 index 00000000..ad398770 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/UserCondition.java @@ -0,0 +1,35 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import org.wamblee.persistence.Persistent; +import org.wamblee.usermgt.User; + +/** + * Condition used to match a user against a specified set of users. + * + * @author Erik Brakkee + */ +public interface UserCondition extends Persistent { + + /** + * Determines if the condition matches. + * @param aUser user to check. + * @return True if the condition matches, false otherwise. + */ + boolean matches(User aUser); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java new file mode 100644 index 00000000..212ce316 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/WriteOperation.java @@ -0,0 +1,36 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * Represents a write operation on a resource. + * + * @author Erik Brakkee + */ +public class WriteOperation extends AllOperation { + + private static final String OPERATION = "write"; + + /** + * Constructs the operation. + * + */ + public WriteOperation() { + super(OPERATION); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java new file mode 100644 index 00000000..6bd87f6c --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/hibernate/AuthorizationMappingFiles.java @@ -0,0 +1,33 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization.hibernate; + +import org.wamblee.usermgt.hibernate.UsermgtHibernateMappingFiles; + +/** + * Mapping files for authorization. + * + * @author Erik Brakkee + */ +public class AuthorizationMappingFiles extends UsermgtHibernateMappingFiles { + + public AuthorizationMappingFiles() { + super(new String[]{ "hbm/AuthorizationRule.hbm.xml", "hbm/UserCondition.hbm.xml", + "hbm/AuthorizationService.hbm.xml", "hbm/OperationCondition.hbm.xml", "hbm/PathCondition.hbm.xml", + "hbm/TestAuthorizationRule.hbm.xml" }); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java new file mode 100644 index 00000000..dfe2439c --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationService.java @@ -0,0 +1,215 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization.hibernate; + +import java.util.List; + +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.wamblee.persistence.AbstractPersistent; +import org.wamblee.persistence.hibernate.HibernateSupport; +import org.wamblee.security.authorization.AuthorizationRule; +import org.wamblee.security.authorization.AuthorizationService; +import org.wamblee.security.authorization.DefaultAuthorizationService; +import org.wamblee.security.authorization.Operation; +import org.wamblee.usermgt.UserAccessor; + +/** + * Authorization service with persistent storage. + * This is a wrapper for {@link org.wamblee.security.authorization.DefaultAuthorizationService} + * which refreshes the state of the service at certain time intervals. + * + * @author Erik Brakkee + */ +public class PersistentAuthorizationService extends AbstractPersistent + implements AuthorizationService { + + /** + * Name of query to find the service by name. + */ + private static final String FIND_QUERY = "findAuthorizationServiceByName"; + + /** + * Name of the query parameter for the service name. + */ + private static final String NAME_PARAM = "name"; + + /** + * Authorization service to use. + */ + private DefaultAuthorizationService _service; + + /** + * Hibernate template to use. + */ + private HibernateTemplate _template; + + /** + * User accessor. + */ + private UserAccessor _userAccessor; + + /** + * Name of the service. + */ + private String _name; + + /** + * Refresh interval in milliseconds. + */ + private final long _refreshInterval; + + /** + * Last refresh time. + */ + private long _lastRefreshTime; + + /** + * Constructs the persistent service. + * + * @param aName + * Name of the service. + * @param aTemplate + * Hibernate template for hibernate usage. + * @param aAccessor + * User accessor. + * @param aRefresh + * Whether or not to refresh the state of the service at the + * start of every operation. + */ + public PersistentAuthorizationService(String aName, + HibernateTemplate aTemplate, UserAccessor aAccessor, + long aRefreshInterval) { + _template = aTemplate; + _refreshInterval = aRefreshInterval; + _lastRefreshTime = System.currentTimeMillis(); + _userAccessor = aAccessor; + _name = aName; + } + + /** + * Initialize service if needed. + */ + private void initialize() { + if (_service == null) { + List result = _template + .findByNamedQueryAndNamedParam(FIND_QUERY, NAME_PARAM, + _name); + + if (result.size() > 1) { + throw new IllegalArgumentException( + "Returned more than one service for name '" + _name + + "' (" + result.size() + ")"); + } + + if (result.size() == 0) { + _service = new DefaultAuthorizationService(_userAccessor, _name); + _template.persist(_service); + } else { + _service = result.get(0); + _service.setUserAccessor(_userAccessor); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationService#isAllowed(java.lang.Object, + * org.wamblee.security.authorization.Operation) + */ + public boolean isAllowed(Object aResource, Operation aOperation) { + initialize(); + refresh(); + return _service.isAllowed(aResource, aOperation); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.AuthorizationService#check(T, org.wamblee.security.authorization.Operation) + */ + public T check(T aResource, Operation aOperation) { + initialize(); + refresh(); + return _service.check(aResource, aOperation); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationService#getRules() + */ + public AuthorizationRule[] getRules() { + initialize(); + refresh(); + return _service.getRules(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationService#appendRule(org.wamblee.security.authorization.AuthorizationRule) + */ + public void appendRule(AuthorizationRule aRule) { + initialize(); + refresh(); + _service.appendRule(aRule); + save(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationService#removeRule(int) + */ + public void removeRule(int aIndex) { + initialize(); + refresh(); + _service.removeRule(aIndex); + save(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.authorization.AuthorizationService#insertRuleAfter(int, + * org.wamblee.security.authorization.AuthorizationRule) + */ + public void insertRuleAfter(int aIndex, AuthorizationRule aRule) { + initialize(); + refresh(); + _service.insertRuleAfter(aIndex, aRule); + save(); + } + + /** + * Refreshes the state of the service through hibernate. + * + */ + private synchronized void refresh() { + long time = System.currentTimeMillis(); + if ( time - _lastRefreshTime > _refreshInterval ) { + _template.refresh(_service); + _lastRefreshTime = time; + } + } + + /** + * Saves any changes to the service state if necessary. + */ + private void save() { + HibernateSupport.merge(_template, _service); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java new file mode 100644 index 00000000..161b652e --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/encryption/Md5HexMessageDigester.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.encryption; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import org.apache.commons.codec.binary.Hex; + +/** + * MD5 Hex encoder. + * + * @author Erik Brakkee + */ +public class Md5HexMessageDigester implements MessageDigester { + + /** + * Constructs the message digester. + * + */ + public Md5HexMessageDigester() { + // Empty + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.security.MessageDigester#hash(java.lang.String) + */ + public String hash(String aValue) { + try { + MessageDigest digest = MessageDigest.getInstance("MD5"); + byte[] result = digest.digest(aValue.getBytes()); + char[] charResult = Hex.encodeHex(result); + return new String(charResult); + } catch (NoSuchAlgorithmException e) { + throw new IllegalArgumentException("MD5 not supported????"); + } + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java new file mode 100644 index 00000000..685a4c79 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/security/encryption/MessageDigester.java @@ -0,0 +1,31 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.encryption; + +/** + * Utility class that encapsulates a message digest method. + */ +public interface MessageDigester { + + /** + * Computes a message digest for a value and encodes it in some way. + * @param aValue Value to compute digest for. + * @return Encoded digest. + */ + String hash(String aValue); + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java new file mode 100644 index 00000000..1a3096f7 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/AbstractUserSet.java @@ -0,0 +1,65 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER; + +import org.wamblee.security.encryption.MessageDigester; + +/** + * User set base class. + */ +public abstract class AbstractUserSet implements UserSet { + + /** + * Password validator. + */ + private NameValidator _passwordValidator; + + /** + * Password encoder. + */ + private MessageDigester _passwordEncoder; + + + protected AbstractUserSet(NameValidator aPasswordValidator, + MessageDigester aPasswordEncoder) { + _passwordValidator = aPasswordValidator; + _passwordEncoder = aPasswordEncoder; + } + + /** + * Sets the password validtor and encoder in the user. + * @param aUser User. + */ + protected void setPasswordInfo(User aUser) { + aUser.setPasswordValidator(_passwordValidator); + aUser.setPasswordEncoder(_passwordEncoder); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.UserSet#createUser(java.lang.String, java.lang.String, org.wamblee.usermgt.Group) + */ + public User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException { + User user = new User(aUsername, aPassword, aGroup, _passwordValidator, _passwordEncoder); + if (contains(user)) { + throw new UserMgtException(DUPLICATE_USER, user); + } + add(user); + return user; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/Group.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/Group.java new file mode 100644 index 00000000..1e7a3f59 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/Group.java @@ -0,0 +1,103 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.io.Serializable; + +import org.wamblee.persistence.AbstractPersistent; + +/** + * Represents a group. + * + * @author Erik Brakkee + */ +public class Group extends AbstractPersistent implements Serializable, Comparable { + + /** + * Group name. + */ + private String _name; + + /** + * Constructs the group. + * @param aName + */ + Group(String aName) { + super(); + _name = aName; + } + + public Group(Group aGroup) { + super(aGroup); + _name = aGroup._name; + } + + protected Group() { + super(); + _name = null; + } + + /** + * Gets the name of the group. + * @return Group name. + */ + public String getName() { + return _name; + } + + /** + * Sets the group name. + * @param aName Group name. + */ + void setName(String aName) { + _name = aName; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object aGroup) { + if ( !( aGroup instanceof Group )) { + return false; + } + return _name.equals(((Group)aGroup)._name); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return _name.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(T) + */ + public int compareTo(Object aGroup) { + return _name.compareTo(((Group)aGroup)._name); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Group(pk = " + getPrimaryKey() + ", name=" + _name + ")"; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/GroupSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/GroupSet.java new file mode 100644 index 00000000..780d60bb --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/GroupSet.java @@ -0,0 +1,73 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.Set; + +/** + * Represents a set of groups. A typical implemnetation would be, a readonly implementation + * defined in a configuration file or a list of groups defined in a database. + * + * @author Erik Brakkee + */ +public interface GroupSet { + + /** + * Must be called when the group has been modified to notify the group set. + * @param aGroup Group that was modified. + */ + void groupModified(Group aGroup); + + /** + * Finds the group by name. + * @param aName Group name. + * @return Group or null if not found. + */ + Group find(String aName); + + /** + * Determines if the group exists. + * @param aGroup Group. + * @return True iff the group exists. + */ + boolean contains(Group aGroup); + + /** + * Adds a group. If the group already exists, the existing group set + * is left unchanged. + * @param aGroup Group. + */ + boolean add(Group aGroup); + + /** + * Removes a group. If the group does not exist, this method is a no-op. + * @param aGroup Group to remove. + * @return True if the group was removed, false otherwise. + */ + boolean remove(Group aGroup); + + /** + * Returns the current groups. + * @return Groups. + */ + Set list(); + + /** + * @return The number of groups. + */ + int size(); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java new file mode 100644 index 00000000..2d2cb85f --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/InMemoryGroupSet.java @@ -0,0 +1,100 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.Set; +import java.util.TreeSet; + +/** + * In-memory group set implementation. + * + * @author Erik Brakkee + */ +public class InMemoryGroupSet implements GroupSet { + + /** + * Groups. + */ + private Set _groups; + + /** + * Constructs an empty group set. + */ + public InMemoryGroupSet() { + _groups = new TreeSet(); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group) + */ + public void groupModified(Group aGroup) { + _groups.remove(aGroup); + _groups.add(aGroup); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#find(java.lang.String) + */ + public Group find(String aName) { + for (Group group: _groups) { + if ( group.getName().equals(aName)) { + return new Group(group); + } + } + return null; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group) + */ + public boolean contains(Group aGroup) { + return _groups.contains(aGroup); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group) + */ + public boolean add(Group aGroup) { + return _groups.add(aGroup); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group) + */ + public boolean remove(Group aGroup) { + return _groups.remove(aGroup); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#list() + */ + public Set list() { + Set list = new TreeSet(); + for (Group group: _groups) { + list.add(new Group(group)); + } + return list; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#size() + */ + public int size() { + return _groups.size(); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java new file mode 100644 index 00000000..6d25dc11 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/InMemoryUserSet.java @@ -0,0 +1,132 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.Set; +import java.util.TreeSet; + +import org.wamblee.security.encryption.MessageDigester; + +/** + * In-memory user set. + * + * @author Erik Brakkee + */ +public class InMemoryUserSet extends AbstractUserSet { + + /** + * Users. All users in this set have their password validator and encoder set. + */ + private Set _users; + + /** + * Constructs an empty user set. + */ + public InMemoryUserSet(NameValidator aPasswordValidator, MessageDigester aPasswordEncoder) { + super(aPasswordValidator, aPasswordEncoder); + _users = new TreeSet(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User) + */ + public void userModified(User aUser) { + _users.remove(aUser); + setPasswordInfo(aUser); + _users.add(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#find(java.lang.String) + */ + public User find(String aName) { + for (User user : _users) { + if (user.getName().equals(aName)) { + return new User(user); + } + } + return null; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User) + */ + public boolean add(User aUser) { + setPasswordInfo(aUser); + return _users.add(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User) + */ + public boolean contains(User aUser) { + return _users.contains(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User) + */ + public boolean remove(User aUser) { + return _users.remove(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#list() + */ + public Set 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) + */ + 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() + */ + public int size() { + return _users.size(); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java new file mode 100644 index 00000000..f353e3b1 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/JaasUserAccessor.java @@ -0,0 +1,101 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.security.AccessController; +import java.security.Principal; +import java.util.Set; + +import javax.security.auth.Subject; + +/** + * Implementation of the user accessor that retrieves user information + * from JAAS. + * + * @author Erik Brakkee + */ +public class JaasUserAccessor implements UserAccessor { + + /** + * User administration to use. + */ + private UserAdministration _admin; + + /** + * Class of the JAAS user principal. + */ + private Class _userPrincipalClass; + + /** + * Constructs user accessor. + * @param aAdmin User administration. + * @param aUserClassName Class name of the user principal. + */ + public JaasUserAccessor(UserAdministration aAdmin, String aUserClassName) { + _admin = aAdmin; + try { + _userPrincipalClass = Class.forName(aUserClassName); + if ( !Principal.class.isAssignableFrom(_userPrincipalClass)) { + throw new IllegalArgumentException("Specified class '" + aUserClassName + "' is not a subclass of '" + + Principal.class.getName()); + } + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAccessor#getCurrentUser() + */ + public User getCurrentUser() { + Subject subject = Subject.getSubject(AccessController.getContext()); + if (subject == null) { + return null; + } + Principal userPrincipal = getUserPrincipal(subject); + + return _admin.getUser(userPrincipal.getName()); + } + + /** + * Gets the user principal from the subject. + * @param subject Subject. + * @return User principal. + * @throws IllegalArgumentException In case there is a duplicate principal or the principal was not found. + */ + private Principal getUserPrincipal(Subject subject) { + Set principals = subject.getPrincipals(); + Principal userPrincipal = null; + for ( Principal principal: principals) { + if ( principal.getClass().equals(_userPrincipalClass)) { + if ( userPrincipal != null ) { + throw new IllegalArgumentException( + "Multiple principals for class '" + _userPrincipalClass + "', subject: " + subject); + } + userPrincipal = principal; + } + } + if ( userPrincipal == null ) { + throw new IllegalArgumentException( + "No user principal found for class '" + _userPrincipalClass + "', subject: " + subject); + } + return userPrincipal; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/NameValidator.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/NameValidator.java new file mode 100644 index 00000000..f120d24a --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/NameValidator.java @@ -0,0 +1,32 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +/** + * Validator of names. + * + * @author Erik Brakkee + */ +public interface NameValidator { + + /** + * Validates a name. + * @param aName Name + * @throws UserMgtException In case the name is invalid. + */ + void validate(String aName) throws UserMgtException; +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java new file mode 100644 index 00000000..8acf1158 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/RegexpNameValidator.java @@ -0,0 +1,85 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import org.wamblee.usermgt.UserMgtException.Reason; + +/** + * Validation of names based on a regular expression. + * + * @author Erik Brakkee + */ +public class RegexpNameValidator implements NameValidator { + + /** + * Convenience pattern for an id. + */ + public static final String ID_PATTERN = "[a-zA-Z]+[a-zA-Z0-9]*"; + + /** + * Convenience pattern for a password consisting of at least 6 characters. + */ + public static final String PASSWORD_PATTERN = ".{6}.*"; + + /** + * Pattern to use. + */ + private String _pattern; + + /** + * Reason to use when validation fails. + */ + private Reason _reason; + + /** + * Message to report. + */ + private String _message; + + /** + * Validates a regular expression. + * @param aPattern Pattern that names must comply to. + * @param aReason Reason to report when validation fails. + * @param aMessage Message to report. + */ + public RegexpNameValidator(String aPattern, Reason aReason, String aMessage) { + _pattern = aPattern; + _reason = aReason; + _message = aMessage; + } + + /** + * Convenience constructor with all string parameters. Useful for configuration + * in Spring. + * @param aPattern Pattern to use. + * @param aReason Reason. + * @param aMessage Message. + */ + public RegexpNameValidator(String aPattern, String aReason, String aMessage) { + this(aPattern, Reason.valueOf(aReason), aMessage); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.NameValidator#validate(java.lang.String) + */ + public void validate(String aName) throws UserMgtException { + if ( !aName.matches(_pattern)) { + throw new UserMgtException(_reason, _message); + } + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/User.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/User.java new file mode 100644 index 00000000..f239c141 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/User.java @@ -0,0 +1,295 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.io.Serializable; +import java.util.Set; +import java.util.TreeSet; + +import org.wamblee.persistence.AbstractPersistent; +import org.wamblee.security.encryption.MessageDigester; +import org.wamblee.usermgt.UserMgtException.Reason; + +/** + * Represents a user. + * The methods for managing the groups of the user have package scope. + * Managing the groups of the user should be done through the + * {@link org.wamblee.usermgt.UserAdministration} interface. + */ +public class User extends AbstractPersistent implements Serializable, Comparable { + + /** + * User name. + */ + private String _name; + + /** + * Password. + */ + private String _password; + + /** + * Groups the user belongs to. + */ + private Set _groups; + + /** + * Password validator. + */ + private NameValidator _passwordValidator; + + /** + * Password encoder. + */ + private MessageDigester _passwordEncoder; + + /** + * Constructs the user. + * @param aName User name. + * @param aPassword Password. + * @param aGroup Group the user belongs to. + */ + User(String aName, String aPassword, Group aGroup, NameValidator aPasswordValidator, + MessageDigester aPasswordEncoder) throws UserMgtException { + super(); + _name = aName; + aPasswordValidator.validate(aPassword); + _password = aPasswordEncoder.hash(aPassword); + _groups = new TreeSet(); + _groups.add(aGroup); + _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)); + } + _passwordValidator = aUser._passwordValidator; + _passwordEncoder = aUser._passwordEncoder; + } + + User() { + super(); + _name = null; + _password = null; + _groups = null; + _passwordValidator = null; + _passwordEncoder = null; + } + + /** + * Sets the password validator. + * @param aPasswordValidator Validator. + */ + public void setPasswordValidator(NameValidator aPasswordValidator) { + _passwordValidator = aPasswordValidator; + } + + /** + * Sets the password encoder. + * @param aPasswordEncoder Encoder. + */ + public void setPasswordEncoder(MessageDigester aPasswordEncoder) { + _passwordEncoder = aPasswordEncoder; + } + + /** + * @return Returns the _password. + */ + String getPassword() { + return _password; + } + + /** + * Checks the password. + * @param aPassword Password to check. + * @throws UserMgtException In case the password is incorrect. + */ + public void checkPassword(String aPassword) throws UserMgtException { + String encoded = _passwordEncoder.hash(aPassword); + if ( !_password.equals(encoded) ) { + throw new UserMgtException(Reason.INVALID_PASSWORD, this); + } + } + + /** + * Changes the password. + * @param aOldPassword Old password. + * @param aNewPassword New password. + * @throws UserMgtException In case the old password is incorrect. + */ + public void changePassword(String aOldPassword, String aNewPassword) throws UserMgtException { + checkPassword(aOldPassword); + _passwordValidator.validate(aNewPassword); + setPassword(aNewPassword); + } + + /** + * @param aPassword + * The password to set. + */ + public void setPassword(String aPassword) throws UserMgtException { + _passwordValidator.validate(aPassword); + _password = _passwordEncoder.hash(aPassword); + } + + /** + * For OR mapping. + * @return Password. + */ + protected String getPasswordString() { + return _password; + } + + /** + * For OR mapping. + * @param aPassword Password. + */ + protected void setPasswordString(String aPassword) { + _password = aPassword; + } + + /** + * @return Returns the _user. + */ + public String getName() { + return _name; + } + + /** + * @param aName + * The username to set. + */ + void setName(String aName) { + _name = aName; + } + + /** + * Gets the groups the user belongs to. + * @return Groups. + */ + public Set getGroups() { + Set result = new TreeSet(); + result.addAll(_groups); + return result; + } + + /** + * Checks whether the user belongs to the given group. + * @param aGroup Group. + * @return True if the user belongs to the group. + */ + public boolean isInGroup(Group aGroup) { + return _groups.contains(aGroup); + } + + /** + * Checks whether the user belongs to the given group. + * @param aGroup Group. + * @return True if the user belongs to the group. + */ + public boolean isInGroup(String aGroup) { + return _groups.contains(new Group(aGroup)); + } + + /** + * Gets the group set. For OR mapping. + * @return set of groups. + */ + Set getGroupSet() { + return _groups; + } + + /** + * Sets the groups the user belongs to, for OR mapping. + * @param aGroups Groups. + */ + void setGroupSet(Set aGroups) { + _groups = aGroups; + } + + /** + * Adds the user to a group. + * @param aGroup Group to add the user to. + * @throws UserMgtException In case the user already belongs to the group. + */ + void addGroup(Group aGroup) throws UserMgtException { + if (_groups.contains(aGroup)) { + throw new UserMgtException(Reason.USER_ALREADY_IN_GROUP, aGroup); + } + _groups.add(aGroup); + } + + /** + * Removes the user from a group. + * @param aGroup Group. + * @throws UserMgtException In case the user does not belong to the group. + */ + void removeGroup(Group aGroup) throws UserMgtException { + if (!_groups.contains(aGroup)) { + throw new UserMgtException(Reason.USER_NOT_IN_GROUP, this, aGroup); + } + if ( _groups.size() == 1 ) { + throw new UserMgtException(Reason.USER_MUST_BE_IN_A_GROUP, this, aGroup); + } + _groups.remove(aGroup); + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object aUser) { + if ( !(aUser instanceof User)) { + return false; + } + User user = (User)aUser; + return _name.equals(user._name); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return _name.hashCode(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + String result = "User(name=" + _name + ", password=" + _password; + for (Group group: _groups) { + result += ", group=" + group; + } + return result + ")"; + } + + /* (non-Javadoc) + * @see java.lang.Comparable#compareTo(T) + */ + public int compareTo(Object aUser) { + return _name.compareTo(((User)aUser)._name); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAccessor.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAccessor.java new file mode 100644 index 00000000..d3dd8a9e --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAccessor.java @@ -0,0 +1,30 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +/** + * Interface for accessing the currently logged in user. + * + * @author Erik Brakkee + */ +public interface UserAccessor { + /** + * Gets the current user. + * @return Currently logged in user or null if no user is found. + */ + User getCurrentUser(); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java new file mode 100644 index 00000000..58263ebc --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdminInitializer.java @@ -0,0 +1,83 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.security.NoSuchAlgorithmException; + +import org.apache.log4j.Logger; + +/** + * User administration initializer. It populates the user administration with a + * number of groups and users but only in case no users exist. + * + * @author Erik Brakkee + */ +public class UserAdminInitializer { + + private static final Logger LOGGER = Logger.getLogger(UserAdminInitializer.class); + + /** + * Initializes the user administration in case no users are present. + * + */ + public UserAdminInitializer(UserAdministration aAdmin, String[] aUsers, + String[] aGroups, String[] aPasswords) throws UserMgtException, NoSuchAlgorithmException { + if (aUsers.length != aGroups.length + || aUsers.length != aPasswords.length) { + throw new IllegalArgumentException( + "Array sizes for users, groups, and passwords differ: " + + aUsers.length + "," + aGroups.length + "," + + aPasswords.length); + + } + if (aAdmin.getUserCount() == 0) { + initialize(aAdmin, aUsers, aGroups, aPasswords); + } + + } + + /** + * Adds the specified users and groups to the user administration. + * @param aAdmin User administration. + * @param aUsers Users. + * @param aGroups Groups. + * @param aPasswords Passwords. + * @throws UserMgtException In case of a problem creating users or groups. + */ + private void initialize(UserAdministration aAdmin, String[] aUsers, + String[] aGroups, String[] aPasswords) throws UserMgtException { + for (int i = 0; i < aUsers.length; i++) { + String user = aUsers[i]; + String group = aGroups[i]; + String password = aPasswords[i]; + + if (aAdmin.getUser(user) == null) { + // must create user. + Group groupObj = aAdmin.getGroup(group); + if (groupObj == null) { + // must create group + LOGGER.info("Creating group: " + group); + groupObj = aAdmin.createGroup(group); + } + assert groupObj != null; + + LOGGER.info("Creating user: " + user + " password: " + password); + aAdmin.createUser(user, password, groupObj); + } + } + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdministration.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdministration.java new file mode 100644 index 00000000..1ce6fbfa --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdministration.java @@ -0,0 +1,151 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.Set; + +/** + * Interface for user administration. Manages the users and groups. + * + * @author Erik Brakkee + */ +public interface UserAdministration { + + /** + * Creates a new user. + * @param aUser Username. + * @param aPassword Password. + * @param aGroup Group. + * @return User. + * @throws UserMgtException In case there is a conflict with an existing user. + */ + User createUser(String aUser, String aPassword, Group aGroup) throws UserMgtException; + + /** + * Creates a new group. + * @param aName Group name. + * @return Group + * @throws UserMgtException In case there is a conflict with an existing group. + */ + Group createGroup(String aName) throws UserMgtException; + + /** + * @return Number of users. + */ + int getUserCount(); + + /** + * @return Number of groups. + */ + int getGroupCount(); + + /** + * Must be called when the user is modified. + * @param aUser User. + */ + void userModified(User aUser); + + /** + * Must be called when the group is modified. + * @param aGroup Group. + */ + void groupModified(Group aGroup); + + /** + * Gets the user for a given name. + * @param aName User name. + * @return User or null if not found. + */ + User getUser(String aName); + + /** + * Gets the group for a given group name. + * @param aName Group name. + * @return Group or null if not found. + */ + Group getGroup(String aName); + + /** + * Get the users. + * @return All known users. + */ + Set getUsers(); + + /** + * Gets the users for a given group. + * @param aGroup Group. + * @return Set of users (always non-null). + */ + Set getUsers(Group aGroup); + + /** + * 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. + */ + void renameUser(User aUser, String aUserName) throws UserMgtException; + + /** + * Renames a group. + * @param aGroup Group to rename. + * @param aGroupName New name for the group. + * @throws UserMgtException In case the new group name is already used by + * another group of if the existing group is unknown. + */ + void renameGroup(Group aGroup, String aGroupName) throws UserMgtException; + + /** + * Removes the user. + * @param aUser User to remove. + * @throws UserMgtException In case the user does not exist. + */ + void removeUser(User aUser) throws UserMgtException; + + /** + * Removes the group. + * @param aGroup Group to remove. + * @throws UserMgtException In case there are still users that are in the given group. + */ + void removeGroup(Group aGroup) throws UserMgtException; + + /** + * Adds a user to a group. + * @param aUser User. + * @param aGroup Group. + * @throws UserMgtException In case the user or group or not known or if the user + * is already part of the group. + */ + void addUserToGroup(User aUser, Group aGroup) throws UserMgtException; + + /** + * Removes a user from a group. + * @param aUser User + * @param aGroup Group + * @throws UserMgtException In case the user or group are unknown or if the user + * is not part of the group. + */ + void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException; +} + diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java new file mode 100644 index 00000000..dceca930 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserAdministrationImpl.java @@ -0,0 +1,289 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_GROUP; +import static org.wamblee.usermgt.UserMgtException.Reason.DUPLICATE_USER; +import static org.wamblee.usermgt.UserMgtException.Reason.GROUP_STILL_OCCUPIED; +import static org.wamblee.usermgt.UserMgtException.Reason.TRIVIAL_RENAME; +import static org.wamblee.usermgt.UserMgtException.Reason.UNKNOWN_GROUP; +import static org.wamblee.usermgt.UserMgtException.Reason.UNKNOWN_USER; + +import java.util.Set; + +/** + * Administration of users and groups. + * + * @author Erik Brakkee + */ +public class UserAdministrationImpl implements UserAdministration { + + /** + * All known users. + */ + private UserSet _users; + + /** + * All known groups. + */ + private GroupSet _groups; + + /** + * Validator for user names. + */ + private NameValidator _userValidator; + + /** + * Validator for group names. + */ + private NameValidator _groupValidator; + + /** + * Constructs empty user administration. + * + */ + public UserAdministrationImpl(UserSet aUsers, GroupSet aGroups, NameValidator aUserValidator, + NameValidator aGroupValidator) { + _users = aUsers; + _groups = aGroups; + _userValidator = aUserValidator; + _groupValidator = aGroupValidator; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#createUser(java.lang.String, + * java.lang.String) + */ + public User createUser(String aUser, String aPassword, Group aGroup) + throws UserMgtException { + _userValidator.validate(aUser); + checkGroup(aGroup); + User user = _users.createUser(aUser, aPassword, aGroup); + return new User(user); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#createGroup(java.lang.String) + */ + public Group createGroup(String aName) throws UserMgtException { + _groupValidator.validate(aName); + Group group = new Group(aName); + if (_groups.contains(group)) { + throw new UserMgtException(DUPLICATE_GROUP, group); + } + _groups.add(group); + return new Group(group); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#userModified(org.wamblee.usermgt.User) + */ + public void userModified(User aUser) { + _users.userModified(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#groupModified(org.wamblee.usermgt.Group) + */ + public void groupModified(Group aGroup) { + _groups.groupModified(aGroup); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#getUser(java.lang.String) + */ + public User getUser(String aName) { + return _users.find(aName); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#getGroup(java.lang.String) + */ + public Group getGroup(String aName) { + return _groups.find(aName); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#getUsers() + */ + public Set getUsers() { + return _users.list(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#getUsers(org.wamblee.usermgt.Group) + */ + public Set getUsers(Group aGroup) { + return _users.list(aGroup); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#getGroups() + */ + public Set getGroups() { + return _groups.list(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#removeUser(org.wamblee.usermgt.User) + */ + public void removeUser(User aUser) throws UserMgtException { + checkUser(aUser); + _users.remove(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#removeGroup(org.wamblee.usermgt.Group) + */ + public void removeGroup(Group aGroup) throws UserMgtException { + checkGroup(aGroup); + if (getUsers(aGroup).size() > 0) { + throw new UserMgtException(GROUP_STILL_OCCUPIED, aGroup); + } + _groups.remove(aGroup); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#renameUser(org.wamblee.usermgt.User, + * java.lang.String) + */ + public void renameUser(User aUser, String aUserName) + throws UserMgtException { + checkUser(aUser); + if (aUser.getName().equals(aUserName)) { + throw new UserMgtException(TRIVIAL_RENAME, aUser); + } + if (_users.find(aUserName) != null) { + throw new UserMgtException(DUPLICATE_USER, aUser); + } + _userValidator.validate(aUserName); + // we are modifying the user so we should re-insert it into the set + // after renaming it. + _users.remove(aUser); + aUser.setName(aUserName); + _users.add(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#renameGroup(org.wamblee.usermgt.Group, + * java.lang.String) + */ + public void renameGroup(Group aGroup, String aGroupName) + throws UserMgtException { + checkGroup(aGroup); + if (aGroup.getName().equals(aGroupName)) { + throw new UserMgtException(TRIVIAL_RENAME, aGroup); + } + if (_groups.find(aGroupName) != null) { + throw new UserMgtException(DUPLICATE_GROUP, aGroup); + } + _groupValidator.validate(aGroupName); + // we are renaming the group so we should re-insert it into the set + // after renaming it. + _groups.remove(aGroup); + aGroup.setName(aGroupName); + _groups.add(aGroup); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#addUserToGroup(org.wamblee.usermgt.User, + * org.wamblee.usermgt.Group) + */ + public void addUserToGroup(User aUser, Group aGroup) + throws UserMgtException { + checkUser(aUser); + checkGroup(aGroup); + aUser.addGroup(aGroup); + _users.userModified(aUser); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministration#removeUserFromGroup(org.wamblee.usermgt.User, + * org.wamblee.usermgt.Group) + */ + public void removeUserFromGroup(User aUser, Group aGroup) + throws UserMgtException { + checkUser(aUser); + checkGroup(aGroup); + aUser.removeGroup(aGroup); + _users.userModified(aUser); + } + + /** + * @param aUser + * @throws UserMgtException + */ + private void checkUser(User aUser) throws UserMgtException { + if (!_users.contains(aUser)) { + throw new UserMgtException(UNKNOWN_USER, aUser); + } + } + + /** + * @param aGroup + * @throws UserMgtException + */ + private void checkGroup(Group aGroup) throws UserMgtException { + if (!_groups.contains(aGroup)) { + throw new UserMgtException(UNKNOWN_GROUP, aGroup); + } + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.UserAdministration#getUserCount() + */ + public int getUserCount() { + return _users.size(); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.UserAdministration#getGroupCount() + */ + public int getGroupCount() { + return _groups.size(); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java new file mode 100644 index 00000000..fb3378cf --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserGroupRepositoryComponent.java @@ -0,0 +1,55 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.usermgt; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +import net.sf.ehcache.Ehcache; + +import org.hibernate.SessionFactory; +import org.wamblee.cache.EhCache; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.spring.SpringComponent; + +public class UserGroupRepositoryComponent extends SpringComponent { + + public UserGroupRepositoryComponent(String aName) { + super(aName, new String[] { "spring/org.wamblee.security.usermgt-repositories.xml" } , + createProvided(), createRequired()); + + } + + private static Map createRequired() { + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("sessionFactory", SessionFactory.class), "sessionFactory"); + return required; + } + + 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; + } + + +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserMgtException.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserMgtException.java new file mode 100644 index 00000000..6a96e618 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserMgtException.java @@ -0,0 +1,128 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.EnumMap; + +/** + * User management exception. + * + * @author Erik Brakkee + */ +public class UserMgtException extends Exception { + + static final long serialVersionUID = 5585349754997507529L; + + /** + * Possible causes for the exception. + * + */ + public enum Reason { + UNKNOWN_USER, + UNKNOWN_GROUP, + DUPLICATE_USER, + DUPLICATE_GROUP, + USER_ALREADY_IN_GROUP, + USER_NOT_IN_GROUP, + TRIVIAL_RENAME, + INVALID_PASSWORD, + GROUP_STILL_OCCUPIED, + USER_MUST_BE_IN_A_GROUP, + INVALID_USERNAME, + INVALID_GROUPNAME + } + + /** + * Mapping of enum to exception message text. + */ + private static final EnumMap MESSAGES = new EnumMap(Reason.class); + + static { + MESSAGES.put(Reason.UNKNOWN_USER, "Unknown user"); + MESSAGES.put(Reason.UNKNOWN_GROUP, "Unknown group"); + MESSAGES.put(Reason.DUPLICATE_USER, "Duplicate user"); + MESSAGES.put(Reason.DUPLICATE_GROUP, "Duplicate group"); + MESSAGES.put(Reason.USER_ALREADY_IN_GROUP, "User already in group"); + MESSAGES.put(Reason.USER_NOT_IN_GROUP, "User not in group"); + MESSAGES.put(Reason.TRIVIAL_RENAME, "Trivial rename"); + MESSAGES.put(Reason.INVALID_PASSWORD, "Invalid password"); + MESSAGES.put(Reason.GROUP_STILL_OCCUPIED, "Group still occupied"); + MESSAGES.put(Reason.USER_MUST_BE_IN_A_GROUP, "User must be in at least one group"); + MESSAGES.put(Reason.INVALID_USERNAME, "Invalid user name"); + MESSAGES.put(Reason.INVALID_GROUPNAME, "Invalid group name"); + } + + /** + * Cause of the exception. + */ + private Reason _cause; + + /** + * User or null if no user is relevant for the problem. + */ + private User _user; + + /** + * Group or null if no group is relevant for the problem. + */ + private Group _group; + + public UserMgtException(Reason aCause, String aMessage) { + super(MESSAGES.get(aCause) + ": " + aMessage); + _cause = aCause; + } + + public UserMgtException(Reason aCause, User aUser) { + this(aCause, "for user '" + aUser.getName() + "'"); + _user = aUser; + } + + public UserMgtException(Reason aCause, Group aGroup) { + this(aCause, "for group '" + aGroup.getName() + "'"); + _group = aGroup; + } + + public UserMgtException(Reason aCause, User aUser, Group aGroup) { + this(aCause, "for user '" + aUser.getName() + "' and group '" + aGroup.getName() + "'"); + _user = aUser; + _group = aGroup; + } + + /** + * Gets the cause of the problem. + * @return Cause. + */ + public Reason getReason() { + return _cause; + } + + /** + * Gets the user for which the problem occurred. + * @return User or null if not applicable. + */ + public User getUser() { + return _user; + } + + /** + * Gets the group for which the problem occured. + * @return Group or null if not applicable. + */ + public Group getGroup() { + return _group; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserSet.java new file mode 100644 index 00000000..ac3f5a70 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/UserSet.java @@ -0,0 +1,92 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.Set; + +/** + * Represents a set of users. + * Typical implementations would be an implementation based on a static configuration file or + * an implementation backed by a database. + * + * @author Erik Brakkee + */ +public interface UserSet { + + /** + * Creates a user. + * @param aUsername User name. + * @param aPassword Password. + * @param aGroup Group. + * @return New user. + * @throws UserMgtException In case the user cannot be created. + */ + User createUser(String aUsername, String aPassword, Group aGroup) throws UserMgtException; + + /** + * Must be called whenever a user object has been modified to notify the + * user set. + * @param aUser Modified user. + */ + void userModified(User aUser); + + /** + * Finds user. + * @param aName Username. + * @return User or null if not found. + */ + User find(String aName); + + /** + * Checks if a user exists. + * @param aUser User. + * @return True iff the user exists. + */ + boolean contains(User aUser); + + /** + * Adds a user. If the user already exists, the user details are updated with that + * of the specified user object. + * @param aUser User to add. + */ + boolean add(User aUser); + + /** + * Removes a user. If the user does not exist, nothing happens. + * @param aUser + */ + boolean remove(User aUser); + + /** + * Lists the current users. + * @return Users. + */ + Set list(); + + /** + * Lists the users belonging to a particular group. + * @param aGroup Group. + * @return Groups. + */ + Set list(Group aGroup); + + /** + * + * @return The number of users. + */ + int size(); +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java new file mode 100644 index 00000000..150a8447 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.usermgt.hibernate; + +import java.io.IOException; + +import javax.sql.DataSource; + +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.transaction.PlatformTransactionManager; +import org.wamblee.cache.EhCache; +import org.wamblee.security.authorization.AuthorizationService; +import org.wamblee.security.authorization.hibernate.AuthorizationMappingFiles; +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.components.ORMappingConfig; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.component.HibernateComponent; +import org.wamblee.usermgt.UserAccessor; +import org.wamblee.usermgt.UserAdministration; +import org.wamblee.usermgt.UserGroupRepositoryComponent; + +public class AuthorizationComponent extends DefaultContainer { + + private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface( + "transactionManager", PlatformTransactionManager.class); + private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface( + "hibernateTemplate", HibernateTemplate.class); + private ProvidedInterface AUTHORIZATION_SERVICE = new DefaultProvidedInterface( + "authorizationService", AuthorizationService.class); + + public AuthorizationComponent(String aName, boolean aExposeInternals) + throws IOException { + super(aName); + + ObjectConfiguration authConfig = new ObjectConfiguration(AuthorizationMappingFiles.class); + authConfig.getSetterConfig().initAllSetters(); + addComponent("mappingFiles", new AuthorizationMappingFiles(), authConfig); + + Component hibernate = new HibernateComponent("hibernate"); + addComponent(hibernate); + + Component authorization = new AuthorizationLightComponent("authorization"); + addComponent(authorization); + + addRequiredInterface(new DefaultRequiredInterface("datasource", DataSource.class)); + addRequiredInterface(new DefaultRequiredInterface("userAccessor", + UserAccessor.class)); + addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class)); + + if (aExposeInternals) { + addProvidedInterface(TRANSACTION_MGR); + addProvidedInterface(HIBERNATE_TEMPLATE); + } + addProvidedInterface(AUTHORIZATION_SERVICE); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java new file mode 100644 index 00000000..e7b0c963 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/AuthorizationLightComponent.java @@ -0,0 +1,66 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.usermgt.hibernate; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.wamblee.security.authorization.AuthorizationService; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.spring.SpringComponent; +import org.wamblee.usermgt.GroupSet; +import org.wamblee.usermgt.UserAccessor; +import org.wamblee.usermgt.UserAdministration; +import org.wamblee.usermgt.UserSet; + +/** + * Light version of the user administration component that requires external + * datasource, and userset and group set components, as well as an external + * hibernate session factory. + * + * @author Erik Brakkee + * + */ +public class AuthorizationLightComponent extends SpringComponent { + + public AuthorizationLightComponent(String aName) { + super( + aName, + new String[] { "spring/org.wamblee.security.authorization.xml" }, + createProvided(), createRequired()); + } + + private static Map 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; + } + + private static Map createProvided() { + Map provided = new HashMap(); + provided.put(AuthorizationService.class.getName(), + new DefaultProvidedInterface(AuthorizationService.class + .getName(), AuthorizationService.class)); + return provided; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java new file mode 100644 index 00000000..957ee44d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateGroupSet.java @@ -0,0 +1,120 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt.hibernate; + +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.wamblee.persistence.hibernate.HibernateSupport; +import org.wamblee.usermgt.Group; +import org.wamblee.usermgt.GroupSet; + +/** + * Set of groups backed by the database. + * + * @author Erik Brakkee + */ +public class HibernateGroupSet extends HibernateSupport implements GroupSet { + + + private static final String QUERY_FIND_BY_NAME = "findGroupByName"; + + private static final String PARAM_NAME = "name"; + + private static final String QUERY_COUNT_GROUPS = "countGroups"; + + public HibernateGroupSet() { + // Empty + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#groupModified(org.wamblee.usermgt.Group) + */ + public void groupModified(Group aGroup) { + assert aGroup.getPrimaryKey() != null; + super.merge(aGroup); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#find(java.lang.String) + */ + public Group find(String aName) { + List list = getHibernateTemplate().findByNamedQueryAndNamedParam(QUERY_FIND_BY_NAME, PARAM_NAME, aName); + if ( list.size() > 1 ) { + throw new RuntimeException("More than one group with the same name '" + aName + "'"); + } + if ( list.size() == 0 ) { + return null; + } + return new Group((Group)list.get(0)); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#contains(org.wamblee.usermgt.Group) + */ + public boolean contains(Group aGroup) { + return find(aGroup.getName()) != null; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#add(org.wamblee.usermgt.Group) + */ + public boolean add(Group aGroup) { + assert aGroup.getPrimaryKey() == null; + if ( contains(aGroup) ) { + return false; + } + super.merge(aGroup); + return true; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#remove(org.wamblee.usermgt.Group) + */ + public boolean remove(Group aGroup) { + assert aGroup.getPrimaryKey() != null; + if ( !contains(aGroup)) { + return false; + } + Group group = (Group) getHibernateTemplate().merge(aGroup); + getHibernateTemplate().delete(group); + aGroup.setPrimaryKey(null); + aGroup.setPersistedVersion(-1); + return true; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#list() + */ + public Set list() { + Set groups = new TreeSet(); + List list = getHibernateTemplate().loadAll(Group.class); + for (Group group: list) { + groups.add(new Group(group)); + } + return groups; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.GroupSet#size() + */ + public int size() { + Long result = (Long) getHibernateTemplate().findByNamedQuery(QUERY_COUNT_GROUPS).get(0); + return result.intValue(); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java new file mode 100644 index 00000000..8bc1db58 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/HibernateUserSet.java @@ -0,0 +1,204 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt.hibernate; + +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.hibernate.SessionFactory; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.wamblee.cache.Cache; +import org.wamblee.persistence.hibernate.HibernateSupport; +import org.wamblee.security.encryption.MessageDigester; +import org.wamblee.usermgt.AbstractUserSet; +import org.wamblee.usermgt.Group; +import org.wamblee.usermgt.NameValidator; +import org.wamblee.usermgt.User; + +/** + * User set backed by the database. + * + * @author Erik Brakkee + */ +public class HibernateUserSet extends AbstractUserSet { + + private static final String QUERY_FIND_BY_NAME = "findUserByName"; + + private static final String QUERY_FIND_BY_GROUP_NAME = "findUserByGroupName"; + + private static final String PARAM_NAME = "name"; + + private static final String QUERY_COUNT_USERS = "countUsers"; + + /** + * Cache of users. Every user in the cache has its password validator and encoder set. + */ + private Cache _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) { + super(aPasswordValidator, aPasswordEncoder); + _cache = aCache; + _hibernateSupport = new HibernateSupport(); + } + + /** + * Sets the session factory. + * @param aFactory Session factory. + */ + public void setSessionFactory(SessionFactory aFactory) { + _hibernateSupport.setSessionFactory(aFactory); + } + + /** + * Gets the hibernate template. + * @return Hibernate template. + */ + private HibernateTemplate getHibernateTemplate() { + return _hibernateSupport.getHibernateTemplate(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#userModified(org.wamblee.usermgt.User) + */ + public void userModified(User aUser) { + assert aUser.getPrimaryKey() != null; + _hibernateSupport.merge(aUser); + _cache.remove(aUser.getName()); + setPasswordInfo(aUser); + _cache.put(aUser.getName(), new User(aUser)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#find(java.lang.String) + */ + public User find(String aName) { + User user = _cache.get(aName); + if (user != null) { + return user; + } + List result = getHibernateTemplate().findByNamedQueryAndNamedParam( + QUERY_FIND_BY_NAME, PARAM_NAME, aName); + if (result.size() > 1) { + throw new RuntimeException( + "Implementation problem, more than one user with the same name!"); + } + if (result.size() == 0) { + return null; + } + user = (User) result.get(0); + setPasswordInfo(user); + _cache.put(aName, user); + return new User(user); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#contains(org.wamblee.usermgt.User) + */ + public boolean contains(User aUser) { + return find(aUser.getName()) != null; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#add(org.wamblee.usermgt.User) + */ + public boolean add(User aUser) { + assert aUser.getPrimaryKey() == null; + if (contains(aUser)) { + return false; + } + getHibernateTemplate().saveOrUpdate(aUser); + setPasswordInfo(aUser); + _cache.put(aUser.getName(), aUser); + return true; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#remove(org.wamblee.usermgt.User) + */ + public boolean remove(User aUser) { + assert aUser.getPrimaryKey() != null; + if (!contains(aUser)) { + return false; + } + User user = (User) getHibernateTemplate().merge(aUser); + getHibernateTemplate().delete(user); + aUser.setPersistedVersion(-1); + aUser.setPrimaryKey(null); + _cache.remove(aUser.getName()); + return true; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserSet#list() + */ + public Set list() { + 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) + */ + public Set list(Group aGroup) { + 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() + */ + public int size() { + Long result = (Long)getHibernateTemplate().findByNamedQuery(QUERY_COUNT_USERS).get(0); + return result.intValue(); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java new file mode 100644 index 00000000..66e3850f --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationComponent.java @@ -0,0 +1,76 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.usermgt.hibernate; + +import java.io.IOException; + +import javax.sql.DataSource; + +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.transaction.PlatformTransactionManager; +import org.wamblee.cache.EhCache; +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.components.ORMappingConfig; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.component.HibernateComponent; +import org.wamblee.usermgt.UserAdministration; +import org.wamblee.usermgt.UserGroupRepositoryComponent; + +public class UserAdministrationComponent extends DefaultContainer { + + private ProvidedInterface TRANSACTION_MGR = new DefaultProvidedInterface( + "transactionManager", PlatformTransactionManager.class); + private ProvidedInterface USER_CACHE = new DefaultProvidedInterface( + "userCache", EhCache.class); + private ProvidedInterface HIBERNATE_TEMPLATE = new DefaultProvidedInterface( + "hibernateTemplate", HibernateTemplate.class); + private ProvidedInterface USER_MGT = new DefaultProvidedInterface( + "usermgt", UserAdministration.class); + + public UserAdministrationComponent(String aName, boolean aExposeInternals) + throws IOException { + super(aName); + + ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); + mappingFilesConfig.getSetterConfig().initAllSetters(); + addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig); + + Component _hibernate = new HibernateComponent("hibernate"); + addComponent(_hibernate); + + Component _repository = new UserGroupRepositoryComponent("usersgroups"); + addComponent(_repository); + + Component _usermgt = new UserAdministrationLightComponent("usermgtlight"); + addComponent(_usermgt); + + addRequiredInterface(new DefaultRequiredInterface("datasource", + DataSource.class)); + addRequiredInterface(new DefaultRequiredInterface("ormconfig", ORMappingConfig.class)); + + if (aExposeInternals) { + addProvidedInterface(TRANSACTION_MGR); + addProvidedInterface(USER_CACHE); + addProvidedInterface(HIBERNATE_TEMPLATE); + } + addProvidedInterface(USER_MGT); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java new file mode 100644 index 00000000..1a06ae7a --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UserAdministrationLightComponent.java @@ -0,0 +1,57 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.usermgt.hibernate; + +import java.util.HashMap; +import java.util.Map; + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.spring.SpringComponent; +import org.wamblee.usermgt.GroupSet; +import org.wamblee.usermgt.UserAdministration; +import org.wamblee.usermgt.UserSet; + +/** + * Light version of the user administration component that requires external + * datasource, and userset and group set components, as well as an external + * hibernate session factory. + * @author Erik Brakkee + * + */ +public class UserAdministrationLightComponent extends SpringComponent { + + public UserAdministrationLightComponent(String aName) { + super(aName, new String[] { "spring/org.wamblee.security.usermgt.xml" }, + createProvided(), createRequired() ); + } + + private static Map 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; + } + + private static Map createProvided() { + Map provided = new HashMap(); + provided.put(UserAdministration.class.getName(), new DefaultProvidedInterface("org.wamblee.usermgt.UserAdministration", + UserAdministration.class)); + return provided; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java new file mode 100644 index 00000000..8d523c2e --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/java/org/wamblee/usermgt/hibernate/UsermgtHibernateMappingFiles.java @@ -0,0 +1,40 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt.hibernate; + +import java.util.Collections; + +import org.wamblee.persistence.hibernate.HibernateMappingFiles; + +/** + * Hibernate mapping files for user management. + * + * @author Erik Brakkee + */ +public class UsermgtHibernateMappingFiles extends HibernateMappingFiles { + + public UsermgtHibernateMappingFiles() { + super(new String[] { + "hbm/Group.hbm.xml", "hbm/User.hbm.xml" + }); + } + + public UsermgtHibernateMappingFiles(String[] aFiles) { + this(); + Collections.addAll(this, aFiles); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/AuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/AuthorizationRule.hbm.xml new file mode 100644 index 00000000..33f5d942 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/AuthorizationRule.hbm.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/AuthorizationService.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/AuthorizationService.hbm.xml new file mode 100644 index 00000000..f8e036ca --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/AuthorizationService.hbm.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + select service + from org.wamblee.security.authorization.AuthorizationService service + where service.name = :name + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/Group.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/Group.hbm.xml new file mode 100644 index 00000000..41e5e6be --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/Group.hbm.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + from org.wamblee.usermgt.Group grp where grp.name = :name + + + + select count(*) + from org.wamblee.usermgt.Group group + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/OperationCondition.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/OperationCondition.hbm.xml new file mode 100644 index 00000000..5ab4b0d8 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/OperationCondition.hbm.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/OperationCondition.hbm.xmlxx b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/OperationCondition.hbm.xmlxx new file mode 100644 index 00000000..250030e0 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/OperationCondition.hbm.xmlxx @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PageAuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PageAuthorizationRule.hbm.xml new file mode 100644 index 00000000..332e5d83 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PageAuthorizationRule.hbm.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PathCondition.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PathCondition.hbm.xml new file mode 100644 index 00000000..c43c0a83 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PathCondition.hbm.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PhotoAuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PhotoAuthorizationRule.hbm.xml new file mode 100644 index 00000000..fc00dda7 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/PhotoAuthorizationRule.hbm.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/TestAuthorizationRule.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/TestAuthorizationRule.hbm.xml new file mode 100644 index 00000000..7f796f58 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/TestAuthorizationRule.hbm.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/User.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/User.hbm.xml new file mode 100644 index 00000000..eefbfa22 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/User.hbm.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + from org.wamblee.usermgt.User user where user.name = :name + + + + select user + from org.wamblee.usermgt.User user + join user.groupSet grp + where grp.name = :name + + + + select count(*) + from org.wamblee.usermgt.User user + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/UserCondition.hbm.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/UserCondition.hbm.xml new file mode 100644 index 00000000..fc83423d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/UserCondition.hbm.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/ehcache.xml b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/ehcache.xml new file mode 100644 index 00000000..ee79950d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/ehcache.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/hbm/hibernate.properties b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/hibernate.properties new file mode 100644 index 00000000..42491b2c --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/hbm/hibernate.properties @@ -0,0 +1,20 @@ + +################################################################################### +# dialect +################################################################################### +hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect + +################################################################################### +# debugging settings: Log4j configuration can provide more detail. +################################################################################### +hibernate.show_sql=false + +################################################################################### +# hibernate cache provider +################################################################################### +hibernate.cache.provider=org.hibernate.cache.EhCacheProvider + +################################################################################### +# query cache +################################################################################### +hibernate.cache.use_query_cache=true \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/properties/org.wamblee.security.ehcache.xml b/tags/wamblee-utils-0.2/security/src/main/resources/properties/org.wamblee.security.ehcache.xml new file mode 100644 index 00000000..ee79950d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/properties/org.wamblee.security.ehcache.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.authorization.xml b/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.authorization.xml new file mode 100644 index 00000000..29f2ff16 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.authorization.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + DEFAULT + + + 10000 + + + + + + + + + administrators + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.usermgt-repositories.xml b/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.usermgt-repositories.xml new file mode 100644 index 00000000..c7ad63c1 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.usermgt-repositories.xml @@ -0,0 +1,43 @@ + + + + + + + properties/org.wamblee.security.ehcache.xml + + + + + users + + + + + .{5,} + INVALID_PASSWORD + Password must have at least 5 characters + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.usermgt.xml b/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.usermgt.xml new file mode 100644 index 00000000..443355f9 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/main/resources/spring/org.wamblee.security.usermgt.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + [a-zA-Z]+[a-zA-Z0-9]* + INVALID_USERNAME + + + + + + + [a-zA-Z]+[a-zA-Z0-9]* + INVALID_GROUPNAME + + + + + + + + + + + + + + org.wamblee.usermgt.UserAdministration + usermanagement-lock-advice + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java new file mode 100644 index 00000000..151dbd7e --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/AuthorizationServiceTest.java @@ -0,0 +1,177 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import static org.wamblee.security.authorization.AuthorizationResult.DENIED; +import static org.wamblee.security.authorization.AuthorizationResult.GRANTED; +import junit.framework.TestCase; + +import org.wamblee.usermgt.UserAccessor; + +/** + * Tests the authorization service. + * + * @author Erik Brakkee + */ +public class AuthorizationServiceTest extends TestCase { + + private AuthorizationRule _rule1; + private AuthorizationRule _rule2; + private AuthorizationRule _rule3; + private AuthorizationService _service; + + protected AuthorizationService getService() { + return _service; + } + + /* (non-Javadoc) + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + + _rule1 = createRule(GRANTED, "users", "/oni/", AllOperation.class); + _rule2 = createRule(DENIED, "users", "/abc/", ReadOperation.class); + _rule3 = createRule(GRANTED, "users", "/abc/", AllOperation.class); + + _service = createService(); + _service.appendRule(_rule1); + _service.appendRule(_rule2); + _service.appendRule(_rule3); + } + + protected void resetTestRules() { + ((TestAuthorizationRule)_rule1).reset(); + ((TestAuthorizationRule)_rule2).reset(); + ((TestAuthorizationRule)_rule3).reset(); + } + + protected UserAccessor createUserAccessor() { + return new TestUserAccessor(); + } + + /** + * Creates an authorization service with some rules for testing. . + * @return Authorization service. + */ + protected AuthorizationService createService() { + DefaultAuthorizationService service = new DefaultAuthorizationService() ; + service.setUserAccessor(createUserAccessor()); + return service; + } + + protected AuthorizationRule createRule(AuthorizationResult aResult, String aGroup, String aPath, Class aOperation) { + return new TestAuthorizationRule(aResult, aGroup, aPath, aOperation); + } + + protected void checkMatchCount(int aCount, AuthorizationRule aRule) { + assertEquals( aCount, ((TestAuthorizationRule)aRule).getMatchCount()); + } + + protected Object createResource(String aPath) { + return new TestResource(aPath); + } + + protected void checkRuleCount(int aCount) { + // Empty + } + + /** + * Several checks to verify the outcome of matching against the first rule. + * + */ + public void testFirstRuleGrants() { + assertTrue( _service.isAllowed(createResource("/oni/xyz.jpg"), new ReadOperation())); + checkMatchCount(1, _rule1); + assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new WriteOperation())); + checkMatchCount(2, _rule1); + assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new DeleteOperation())); + checkMatchCount(3, _rule1); + assertTrue(_service.isAllowed(createResource("/oni/xyz.jpg"), new CreateOperation())); + checkMatchCount(4, _rule1); + checkMatchCount(0, _rule2); + checkMatchCount(0, _rule3); + } + + /** + * Verify that a match with the second rule leads to a denial of authorization. + * + */ + public void testSecondRuleDenies() { + assertFalse(_service.isAllowed(createResource("/abc/xyz.jpg"), new ReadOperation())); + checkMatchCount(0, _rule1); + checkMatchCount(1, _rule2); + checkMatchCount(0, _rule3); + } + + /** + * Verifies that the third rule is used when appropriate and that it grants access. + * + */ + public void testThirdRuleGrants() { + assertTrue(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation())); + checkMatchCount(0, _rule1); + checkMatchCount(0, _rule2); + checkMatchCount(1, _rule3); + } + + /** + * Removes a rule and checks it is removed. + * + */ + public void testRemoveRule() { + checkRuleCount(3); + assertTrue(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation())); + _service.removeRule(2); + assertFalse(_service.isAllowed(createResource("/abc/xyz.jpg"), new WriteOperation())); + checkRuleCount(2); + } + + /** + * Inserts a rule and checks it is inserted. + * + */ + public void testInsertRule() { + checkRuleCount(3); + assertFalse(_service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation())); + _service.appendRule(createRule(GRANTED, "users", "/janse/", WriteOperation.class)); + assertTrue(_service.isAllowed(createResource("/janse/xyz.jpg"), new WriteOperation())); + checkRuleCount(4); + + } + + /** + * Gets the rules. Verifies that all rules are obtained. + * + */ + public void testGetRules() { + AuthorizationRule[] rules = _service.getRules(); + assertEquals(3, rules.length); + } + + /** + * Verifies that when no rules match, access is denied. + * + */ + public void testNoRulesSupportResource() { + assertFalse(_service.isAllowed(createResource("/xyxyxyxy"), new ReadOperation())); + checkMatchCount(0, _rule1); + checkMatchCount(0, _rule2); + checkMatchCount(0, _rule3); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java new file mode 100644 index 00000000..3dcfe2d2 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/DefaultOperationRegistryTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import junit.framework.TestCase; + +/** + * Test of the operation registry. + * + * @author Erik Brakkee + */ +public class DefaultOperationRegistryTest extends TestCase { + + private OperationRegistry _registry; + + /* (non-Javadoc) + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + + _registry = new DefaultOperationRegistry(new Operation[] { + new AllOperation(), + new ReadOperation(), + new WriteOperation(), + new DeleteOperation(), + new CreateOperation() + }); + } + + /** + * Tests encoding and decoding of no operations. + * + */ + public void testEncodeDecodeNooperations() { + assertEquals("", _registry.encode(new Operation[0])); + assertEquals(0, _registry.decode(Object.class, "").length); + } + + /** + * Verifies that encoding of operations into a string works. + * + */ + public void testEncode() { + assertEquals("read,write", _registry.encode(new Operation[] { new ReadOperation(), new WriteOperation() })); + } + + /** + * Verifies that decoding of operation from a string works. + * + */ + public void testDecode() { + Operation[] operations = _registry.decode(Object.class, "read,write"); + assertTrue( operations[0] instanceof ReadOperation); + assertTrue( operations[1] instanceof WriteOperation); + } + + /** + * Verifies that an IllegalArgumentException occurs when attempting to decode + * an operation that is not known. + * + */ + public void testDecodeUnknownOperation() { + try { + _registry.decode(Object.class, "bla"); + fail(); + } catch (IllegalArgumentException e) { + // ok + } + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java new file mode 100644 index 00000000..cf83b289 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/RegexpPathConditionTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import junit.framework.TestCase; + +/** + * Test for regular expression matching. + * + * @author Erik Brakkee + */ +public class RegexpPathConditionTest extends TestCase { + + /** + * Various tests. + * + */ + public void testMatch() { + PathCondition cond = new RegexpPathCondition("abc"); + assertTrue(cond.matches("abc")); + assertFalse(cond.matches("xabcx")); + cond = new RegexpPathCondition("/[a-z]*/.*"); + assertTrue(cond.matches("/hallo/xyz")); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java new file mode 100644 index 00000000..2e64098d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/StartsWithPathConditionTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import junit.framework.TestCase; + +/** + * Tests for StartsWithPathCondition. + * + * @author Erik Brakkee + */ +public class StartsWithPathConditionTest extends TestCase { + + /** + * Various tests. + */ + public void testMatches() { + PathCondition cond = new StartsWithPathCondition("/hallo"); + assertTrue(cond.matches("/hallo")); + assertTrue(cond.matches("/hallox")); + assertTrue(cond.matches("/hallo/abc")); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java new file mode 100644 index 00000000..93141fde --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestAuthorizationRule.java @@ -0,0 +1,75 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import static org.wamblee.security.authorization.AuthorizationResult.DENIED; +import static org.wamblee.security.authorization.AuthorizationResult.GRANTED; + +import org.wamblee.usermgt.User; + +/** + * Test authorization rule that also counts the number of times the rule matches. + * + * @author Erik Brakkee + */ +public class TestAuthorizationRule extends UrlAuthorizationRule { + + /** + * Counts the number of matches. + */ + private int _matches = 0; + + public TestAuthorizationRule( AuthorizationResult aResult, String aGroup, + String aPath, Class aOperation) { + super(aResult, new GroupUserCondition(aGroup), + new StartsWithPathCondition(aPath), TestResource.class, new IsaOperationCondition(aOperation)); + } + + protected TestAuthorizationRule() { + super(); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.UrlAuthorizationRule#getPath(java.lang.Object) + */ + @Override + protected String getResourcePath(Object aResource) { + return ((TestResource)aResource).getPath(); + } + + /* (non-Javadoc) + * @see org.wamblee.security.authorization.UrlAuthorizationRule#isAllowed(java.lang.Object, org.wamblee.security.authorization.Operation, org.wamblee.usermgt.UserAccessor) + */ + @Override + public AuthorizationResult isAllowed(Object aResource, Operation anOperation, User aUser) { + + AuthorizationResult result = super.isAllowed(aResource, anOperation, aUser); + if ( result.equals(GRANTED) || result.equals(DENIED)) { + _matches++; + } + return result; + } + + public int getMatchCount() { + return _matches; + } + + public void reset() { + _matches = 0; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestResource.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestResource.java new file mode 100644 index 00000000..a0edd898 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestResource.java @@ -0,0 +1,35 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +/** + * A test resource for authorization. + * + * @author Erik Brakkee + */ +public class TestResource { + + private String _path; + + public TestResource(String aPath) { + _path = aPath; + } + + public String getPath() { + return _path; + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java new file mode 100644 index 00000000..02e09020 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/TestUserAccessor.java @@ -0,0 +1,66 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import junit.framework.TestCase; + +import org.wamblee.security.encryption.Md5HexMessageDigester; +import org.wamblee.usermgt.Group; +import org.wamblee.usermgt.InMemoryGroupSet; +import org.wamblee.usermgt.InMemoryUserSet; +import org.wamblee.usermgt.RegexpNameValidator; +import org.wamblee.usermgt.User; +import org.wamblee.usermgt.UserAccessor; +import org.wamblee.usermgt.UserAdministration; +import org.wamblee.usermgt.UserAdministrationImpl; +import org.wamblee.usermgt.UserMgtException; +import org.wamblee.usermgt.UserMgtException.Reason; + +/** + * User access that always returns a user that belongs to + * a fixed group. + * + * @author Erik Brakkee + */ +public class TestUserAccessor implements UserAccessor { + + private static final String USER = "erik"; + private static final String PASSWORD = "abc123"; + private static final String GROUP = "users"; + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAccessor#getCurrentUser() + */ + public User getCurrentUser() { + UserAdministration admin = new UserAdministrationImpl( + new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"), + new Md5HexMessageDigester()), new InMemoryGroupSet(), + new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, Reason.INVALID_USERNAME, "Invalid user"), + new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, Reason.INVALID_GROUPNAME, "Invalid group") + ); + try { + Group group = admin.createGroup(GROUP); + return admin.createUser(USER, PASSWORD, group); + } catch (UserMgtException e) { + TestCase.fail(e.getMessage()); + throw new RuntimeException(e); + } + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java new file mode 100644 index 00000000..4e66ed86 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/UrlAuthorizationRuleTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization; + +import static org.wamblee.security.authorization.AuthorizationResult.GRANTED; +import static org.wamblee.security.authorization.AuthorizationResult.UNDECIDED; +import static org.wamblee.security.authorization.AuthorizationResult.UNSUPPORTED_RESOURCE; +import junit.framework.TestCase; + +import org.wamblee.usermgt.User; + + +/** + * Tests for the {@link org.wamblee.security.authorization.UrlAuthorizationRule}. + * + * @author Erik Brakkee + */ +public class UrlAuthorizationRuleTest extends TestCase { + + /** + * Constructs the rule with a result of UNDECIDED. Verifies that an IllegalArgumentException + * is thrown. + * + */ + public void testConstructWithUndecidedResult() { + try { + new TestAuthorizationRule(UNDECIDED, "users", "/path", ReadOperation.class); + fail(); + } catch (IllegalArgumentException e) { + // ok + } + } + + /** + * Constructs the rule with a result of UNSUPPORTED_RESOURCE. Verifies that an IllegalArgumentException + * is thrown. + * + */ + public void testConstructWithUnsupportedResult() { + try { + new TestAuthorizationRule(UNSUPPORTED_RESOURCE, "users", "/path", ReadOperation.class); + fail(); + } catch (IllegalArgumentException e) { + // ok + } + } + + /** + * Constructs the authorization rule and applies it to an unsupported object type. + * Verifies that the result is UNSUPPORTED_RESOURCE. + * + */ + public void testUnsupportedObject() { + AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users", "/path", ReadOperation.class); + assertEquals(UNSUPPORTED_RESOURCE, rule.isAllowed("hello", new ReadOperation(), new TestUserAccessor().getCurrentUser())); + } + + public void testMatchingScenarios() { + AuthorizationRule rule = new TestAuthorizationRule(GRANTED, "users", "/path/", ReadOperation.class); + User user = new TestUserAccessor().getCurrentUser(); + + // everything matches + assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/a"), new ReadOperation(), user)); + assertEquals(GRANTED, rule.isAllowed(new TestResource("/path/"), new ReadOperation(), user)); + + // path does not match. + assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path"), new ReadOperation(), user)); + + // operation does not match. + assertEquals(UNDECIDED, rule.isAllowed(new TestResource("/path/"), new WriteOperation(), user)); + + // group does not match. + AuthorizationRule rule2 = new TestAuthorizationRule(GRANTED, "users2", "/path/", ReadOperation.class); + assertEquals(UNDECIDED, rule2.isAllowed(new TestResource("/path/a"), new ReadOperation(), user)); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java new file mode 100644 index 00000000..f55fc293 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/authorization/hibernate/PersistentAuthorizationServiceTest.java @@ -0,0 +1,187 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.authorization.hibernate; + +import java.sql.SQLException; + +import org.apache.log4j.Logger; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.MySQL5Dialect; +import org.hibernate.dialect.MySQL5InnoDBDialect; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.wamblee.general.BeanKernel; +import org.wamblee.security.authorization.AuthorizationService; +import org.wamblee.security.authorization.AuthorizationServiceTest; +import org.wamblee.security.authorization.TestUserAccessor; +import org.wamblee.system.adapters.ClassConfiguration; +import org.wamblee.system.adapters.ClassConfigurationTest; +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.components.DatabaseComponentFactory; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.component.DatabaseTesterComponent; +import org.wamblee.system.spring.component.DatasourceComponent; +import org.wamblee.usermgt.UserAccessor; +import org.wamblee.usermgt.hibernate.AuthorizationComponent; +import org.wamblee.usermgt.hibernate.HibernateUserAdministrationTest; +import org.wamblee.usermgt.hibernate.UserAdministrationComponent; + +/** + * Unit test for the persistent authorization service. + * + * @author Erik Brakkee + */ +public class PersistentAuthorizationServiceTest extends + AuthorizationServiceTest { + + private static final Logger LOGGER = Logger + .getLogger(PersistentAuthorizationServiceTest.class); + + private static final String SERVICE_TABLE = "AUTHORIZATION_SERVICE"; + private static final String RULES_TABLE = "AUTHORIZATION_RULES"; + private static final String SERVICE_RULES_TABLE = "AUTHORIZATION_SERVICE_RULES"; + private static final String OPERATIONCOND_TABLE = "OPERATION_CONDITIONS"; + private static final String PATHCOND_TABLE = "PATH_CONDITIONS"; + private static final String USERCOND_TABLE = "USER_CONDITIONS"; + + private DefaultContainer _container; + private Scope _scope; + + private DatabaseTesterComponent _databaseTester; + private UserAccessor _userAccessor; + private HibernateTemplate _hibernateTemplate; + private AuthorizationService _authorizationService; + + @Override + protected void setUp() throws Exception { + + _container = new DefaultContainer("top"); + DatabaseComponentFactory.addDatabaseConfig(_container); + _container.addComponent(new DatasourceComponent("datasource")); + ClassConfiguration useraccessorConfig = new ClassConfiguration( + TestUserAccessor.class); + useraccessorConfig.getObjectConfig().getSetterConfig().initAllSetters(); + _container.addComponent("userAccessor", useraccessorConfig); + _container.addComponent(new AuthorizationComponent("authorization", + true)); + + ClassConfiguration dbtesterConfig = new ClassConfiguration( + DatabaseTesterComponent.class); + dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters(); + _container.addComponent("databaseTester", dbtesterConfig); + + ObjectConfiguration config = new ObjectConfiguration( + PersistentAuthorizationServiceTest.class); + config.getSetterConfig().clear().add("setUserAccessor").add( + "setDatabaseTester").add("setHibernateTemplate").add( + "setAuthorizationService"); + _container.addComponent("testcase", this, config); + + _scope = _container.start(); + + _databaseTester.cleanDatabase(); + + super.setUp(); + } + + public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { + _databaseTester = aDatabaseTester; + } + + public void setUserAccessor(UserAccessor aUserAccessor) { + _userAccessor = aUserAccessor; + } + + public void setHibernateTemplate(HibernateTemplate aHibernateTemplate) { + _hibernateTemplate = aHibernateTemplate; + } + + public void setAuthorizationService( + AuthorizationService aAuthorizationService) { + _authorizationService = aAuthorizationService; + } + + /* + * (non-Javadoc) + * + * @see + * org.wamblee.security.authorization.AuthorizationServiceTest#createService + * () + */ + @Override + protected AuthorizationService createService() { + PersistentAuthorizationService service = new PersistentAuthorizationService( + "DEFAULT", _hibernateTemplate, createUserAccessor(), 10000); + return service; + } + + /* + * (non-Javadoc) + * + * @see + * org.wamblee.security.authorization.AuthorizationServiceTest#checkRuleCount + * (int) + */ + @Override + protected void checkRuleCount(int aCount) { + try { + assertEquals(1, _databaseTester.getTableSize(SERVICE_TABLE)); + assertEquals(aCount, _databaseTester.getTableSize(RULES_TABLE)); + assertEquals(aCount, _databaseTester + .getTableSize(SERVICE_RULES_TABLE)); + assertEquals(aCount, _databaseTester.getTableSize(USERCOND_TABLE)); + assertEquals(aCount, _databaseTester.getTableSize(PATHCOND_TABLE)); + assertEquals(aCount, _databaseTester + .getTableSize(OPERATIONCOND_TABLE)); + } catch (SQLException e) { + throw new RuntimeException(e); + } + + } + + public void testSchemaExport() { + Configuration config = new Configuration(); + for (String mappingFile: new AuthorizationMappingFiles()) { + config.addResource(mappingFile); + } + config.setProperty("hibernate.dialect", MySQL5InnoDBDialect.class.getName()); + SchemaExport exporter = new SchemaExport(config); + exporter.setOutputFile("target/mysql5.schema.sql"); + exporter.create(true,false); + } + + public void testPerformance() { + + PersistentAuthorizationService service = (PersistentAuthorizationService) getService(); + + int n = 1000; + long time = System.currentTimeMillis(); + for (int i = 0; i < n; i++) { + testFirstRuleGrants(); + resetTestRules(); + testSecondRuleDenies(); + resetTestRules(); + testThirdRuleGrants(); + resetTestRules(); + testNoRulesSupportResource(); + } + LOGGER.info("Executed " + 4 * n + " authorization checks in " + + (float) (System.currentTimeMillis() - time) / (float) 1000 + + " seconds."); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java new file mode 100644 index 00000000..6760efe9 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/security/encryption/MessageDigesterTest.java @@ -0,0 +1,31 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.security.encryption; + +import junit.framework.TestCase; + +/** + * Tests for the message digester. + * + * @author Erik Brakkee + */ +public class MessageDigesterTest extends TestCase { + + public void testMd5HexEncoding() { + assertEquals("e99a18c428cb38d5f260853678922e03", new Md5HexMessageDigester().hash("abc123")); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java new file mode 100644 index 00000000..2ea11905 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/InMemoryGroupSetTest.java @@ -0,0 +1,188 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.sql.SQLException; +import java.util.Set; + +import junit.framework.TestCase; + +/** + * Tests the inmemory group set. Intended to be subclassed for other + * implementations of group set. + */ +public class InMemoryGroupSetTest extends TestCase { + + protected GroupSet _groups; + + /** + * This method must be overriden in subclasses. + * @return New group set object. + */ + protected GroupSet createGroupSet() { + return new InMemoryGroupSet(); + } + + /* (non-Javadoc) + * @see org.wamblee.test.SpringTestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + _groups = createGroupSet(); + checkGroupCount(0); + } + + + + /** + * Additional check to be implemented by a subclass. + * @param aGroup Group to check for existence. + */ + protected void checkGroupExists(String aGroup) throws SQLException { + // Empty + } + + /** + * Additional check to be implemented by a subclass. + * @param aGroup Group to check for non-existence. + */ + protected void checkGroupNotExists(String aGroup) throws SQLException { + // Empty + } + + /** + * Additional check to be implemented by a subclass. + * @param aSize Expected number of groups. + */ + protected void checkGroupCount(int aSize) throws SQLException { + assertEquals(aSize, _groups.size()); + } + + /** + * Adds a group and verifies that the group is added using + * find(), list(), and contains(). + * + */ + public void testAdd() throws SQLException { + Group group = new Group("group1"); + assertTrue( _groups.add(group) ); + checkGroupExists(group.getName()); + checkGroupCount(1); + Group group2 = _groups.find("group1"); + assertNotNull(group2); + assertEquals(group.getName(), group2.getName()); + Set set = _groups.list(); + assertEquals(1, set.size()); + assertTrue(set.contains(group)); + } + + /** + * Tries to find a non-existing group. Verifies that null is + * returned. + * + */ + public void testFindUnknownGroup() throws SQLException { + Group group1 = new Group("group1"); + Group group2 = new Group("group2"); + _groups.add(group1); + _groups.add(group2); + checkGroupExists(group1.getName()); + checkGroupExists(group2.getName()); + + assertNull( _groups.find("group3") ); + checkGroupNotExists("group3"); + } + + /** + * Adds duplicate group. Verifies that the existing group is left untouched. + */ + public void testAddDuplicateGroup() throws SQLException { + Group group1 = new Group("group1"); + _groups.add(group1); + + assertEquals(1, _groups.list().size()); + assertTrue(_groups.contains(group1)); + group1 = new Group("group1"); + assertFalse(_groups.add(group1)); + assertEquals(1, _groups.list().size()); + + checkGroupExists(group1.getName()); + checkGroupCount(1); + } + + /** + * Removes a group. Verifies that the group is + * removed and the return value is true. + * + */ + public void testRemoveGroup() throws SQLException { + Group group1 = new Group("group1"); + _groups.add(group1); + assertTrue(_groups.contains(group1)); + checkGroupCount(1); + + assertTrue(_groups.remove(group1)); + assertFalse(_groups.contains(group1)); + assertNull(_groups.find(group1.getName())); + assertEquals(0, _groups.list().size()); + checkGroupCount(0); + } + + /** + * Removes a non-existing group. Verifies that no groups are + * removed an that the return value is true. + * + */ + public void testRemoveNonExistingGroup() throws SQLException { + Group group1 = new Group("group1"); + _groups.add(group1); + checkGroupCount(1); + Group nonExistingGroup = new Group("group2"); + nonExistingGroup.setPrimaryKey(new Long(1000)); + nonExistingGroup.setPersistedVersion(1000); + assertFalse(_groups.remove(nonExistingGroup)); + assertTrue(_groups.contains(group1)); + assertEquals(1, _groups.list().size()); + checkGroupCount(1); + } + + /** + * Adds a number of groups to the set and verifies that list() + * returns them all. + * + */ + public void testList() throws SQLException { + Group group1 = new Group("group1"); + Group group2 = new Group("group2"); + Group group3 = new Group("group3"); + assertTrue(_groups.add(group1)); + assertTrue(_groups.add(group2)); + assertTrue(_groups.add(group3)); + + checkGroupExists(group1.getName()); + checkGroupExists(group2.getName()); + checkGroupExists(group3.getName()); + + Set set = _groups.list(); + assertTrue(set.contains(group1)); + assertTrue(set.contains(group2)); + assertTrue(set.contains(group3)); + + checkGroupCount(3); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java new file mode 100644 index 00000000..8d60d433 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/InMemoryUserSetTest.java @@ -0,0 +1,312 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.sql.SQLException; +import java.util.Set; + +import junit.framework.TestCase; + +import org.wamblee.security.encryption.Md5HexMessageDigester; +import org.wamblee.usermgt.UserMgtException.Reason; + +/** + * Tests the inmemory user set. Intended to be subclassed for other + * implementations of user set. + */ +public class InMemoryUserSetTest extends TestCase { + + protected static final String PASSWORD = "abc123"; + + private UserSet _users; + private GroupSet _groups; + + private Group _group; + + /** + * This method must be overriden in subclasses. + * @return New user set object. + */ + protected UserSet createUserSet() { + return new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"), + new Md5HexMessageDigester()); + } + + /** + * This method must be overriden in subclasses. + * @return New group set object. + */ + protected GroupSet createGroupSet() { + return new InMemoryGroupSet(); + } + + /* (non-Javadoc) + * @see org.wamblee.test.SpringTestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + _users = createUserSet(); + _groups = createGroupSet(); + _group = new Group("group0"); + _groups.add(_group); + checkUserCount(0); + + } + + protected UserSet getUsers() { + return _users; + } + + protected GroupSet getGroups() { + return _groups; + } + + protected Group createGroup(String aName) { + return new Group(aName); + } + + protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { + return UsermgtTestUtils.createUser(aName, aPassword, aGroup); + } + + protected void addUserToGroup(User aUser, Group aGroup) throws UserMgtException { + aUser.addGroup(aGroup); + } + + protected void removeUserFromGroup(User aUser, Group aGroup ) throws UserMgtException { + aUser.removeGroup(aGroup); + } + + /** + * Additional check to be implemented by a subclass. + * @param aUser User to check for existence. + */ + protected void checkUserExists(String aUser) throws SQLException { + // Empty + } + + /** + * Additional check to be implemented by a subclass. + * @param aUser User to check for non-existence. + */ + protected void checkUserNotExists(String aUser) throws SQLException { + // Empty + } + + /** + * Additional check to be implemented by a subclass. + * @param aSize Expected number of users. + */ + protected void checkUserCount(int aSize) throws SQLException { + assertEquals(aSize, _users.size()); + } + + /** + * Additional check to be implemented by a subclass. + * @param aUser User to check for existence. + */ + protected void checkGroupExists(String aUser) throws SQLException { + // Empty + } + + /** + * Additional check to be implemented by a subclass. + * @param aUser User to check for non-existence. + */ + protected void checkGroupNotExists(String aUser) throws SQLException { + // Empty + } + + /** + * Additional check to be implemented by a subclass. + * @param aSize Expected number of users. + */ + protected void checkGroupCount(int aSize) throws SQLException { + // Empty + } + + + /** + * Adds a user and verifies that the user is added using + * find(), list(), and contains(). + * + */ + public void testAdd() throws SQLException, UserMgtException { + User user = createUser("user1", PASSWORD, _group); + assertTrue( _users.add(user) ); + checkUserExists(user.getName()); + checkUserCount(1); + User user2 = _users.find("user1"); + assertNotNull(user2); + assertEquals(user.getName(), user2.getName()); + Set set = _users.list(); + assertEquals(1, set.size()); + assertTrue(set.contains(user)); + } + + /** + * Tries to find a non-existing user. Verifies that null is + * returned. + * + */ + public void testFindUnknownUser() throws SQLException, UserMgtException { + User user1 = createUser("user1", PASSWORD, _group); + User user2 = createUser("user2", PASSWORD, _group); + _users.add(user1); + _users.add(user2); + checkUserExists(user1.getName()); + checkUserExists(user2.getName()); + + assertNull( _users.find("user3") ); + checkUserNotExists("user3"); + } + + /** + * Adds duplicate user. Verifies that the existing user is left untouched. + */ + public void testAddDuplicateUser() throws SQLException, UserMgtException { + User user1 = createUser("user1", PASSWORD, _group); + _users.add(user1); + + assertEquals(1, _users.list().size()); + assertTrue(_users.contains(user1)); + user1 = createUser("user1", PASSWORD, _group); + assertFalse(_users.add(user1)); + assertEquals(1, _users.list().size()); + + checkUserExists(user1.getName()); + checkUserCount(1); + } + + /** + * Removes a user. Verifies that the user is + * removed and the return value is true. + * + */ + public void testRemoveUser() throws SQLException, UserMgtException { + User user1 = createUser("user1", PASSWORD, _group); + _users.add(user1); + assertTrue(_users.contains(user1)); + checkUserCount(1); + + assertTrue(_users.remove(user1)); + assertFalse(_users.contains(user1)); + assertNull(_users.find(user1.getName())); + assertEquals(0, _users.list().size()); + checkUserCount(0); + } + + /** + * Removes a non-existing user. Verifies that no users are + * removed an that the return value is true. + * + */ + public void testRemoveNonExistingUser() throws SQLException, UserMgtException { + User user1 = createUser("user1", PASSWORD, _group); + _users.add(user1); + checkUserCount(1); + User nonExistingUser = createUser("user2", PASSWORD, _group); + nonExistingUser.setPrimaryKey(new Long(1000)); + nonExistingUser.setPersistedVersion(10); + assertFalse(_users.remove(nonExistingUser)); + assertTrue(_users.contains(user1)); + assertEquals(1, _users.list().size()); + checkUserCount(1); + } + + /** + * Adds a number of users to the set and verifies that list() + * returns them all. + * + */ + public void testList() throws SQLException, UserMgtException { + User user1 = createUser("user1", PASSWORD, _group); + User user2 = createUser("user2", PASSWORD, _group); + User user3 = createUser("user3", PASSWORD, _group); + assertTrue(_users.add(user1)); + assertTrue(_users.add(user2)); + assertTrue(_users.add(user3)); + + checkUserExists(user1.getName()); + checkUserExists(user2.getName()); + checkUserExists(user3.getName()); + + Set set = _users.list(); + assertTrue(set.contains(user1)); + assertTrue(set.contains(user2)); + assertTrue(set.contains(user3)); + + checkUserCount(3); + } + + /** + * Adds several users to different groups and verifies that + * the correct users are returned when looking for users in + * different groups. + * @throws SQLException + */ + public void testListByGroup() throws SQLException, UserMgtException { + Group group1 = new Group("group1"); + Group group2 = new Group("group2"); + Group group3 = new Group("group3"); + _groups.add(group1); + _groups.add(group2); + _groups.add(group3); + + // user1 user2 user3 + // group1 y + // group2 y y + // group3 y y y + + User user1 = createUser("user1", PASSWORD, group1); + user1.addGroup(group2); + user1.addGroup(group3); + User user2 = createUser("user2", PASSWORD, group2); + user2.addGroup(group3); + User user3 = createUser("user3", PASSWORD, group3); + _users.add(user1); + _users.add(user2); + _users.add(user3); + + checkUserExists(user1.getName()); + checkUserExists(user2.getName()); + checkUserExists(user3.getName()); + + checkGroupExists(group1.getName()); + checkGroupExists(group2.getName()); + checkGroupExists(group3.getName()); + + checkUserCount(3); + checkGroupCount(3+1); // also count the group that was created in the setUp(). + + Set list = _users.list(group1); + assertTrue(list.contains(user1)); + assertEquals(1, list.size()); + + list = _users.list(group2); + assertTrue(list.contains(user1)); + assertTrue(list.contains(user2)); + assertEquals(2, list.size()); + + list = _users.list(group3); + assertTrue(list.contains(user1)); + assertTrue(list.contains(user2)); + assertTrue(list.contains(user3)); + assertEquals(3, list.size()); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java new file mode 100644 index 00000000..055828d6 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/UserAdministrationImplTest.java @@ -0,0 +1,603 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import java.util.Set; + +import junit.framework.TestCase; + +import org.apache.log4j.Logger; +import org.wamblee.security.encryption.Md5HexMessageDigester; +import org.wamblee.usermgt.UserMgtException.Reason; + +/** + * Test of user administration implementation. + * + * @author Erik Brakkee + */ +public class UserAdministrationImplTest extends TestCase { + + private static final Logger LOGGER = Logger + .getLogger(UserAdministrationImplTest.class); + + private static final String USER1 = "piet"; + + private static final String PASS1 = "passpiet"; + + private static final String USER2 = "kees"; + + private static final String PASS2 = "passkees"; + + private static final String GROUP1 = "cyclists"; + + private static final String GROUP2 = "runners"; + + private UserAdministration _admin; + + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + _admin = createAdmin(); + } + + protected UserAdministration createAdmin() { + UserSet users = new InMemoryUserSet( new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, Reason.INVALID_PASSWORD, "Password must contain at least 6 characters"), + new Md5HexMessageDigester()); + GroupSet groups = new InMemoryGroupSet(); + return new UserAdministrationImpl(users, groups, + new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, + Reason.INVALID_USERNAME, "Invalid user"), + new RegexpNameValidator(RegexpNameValidator.ID_PATTERN, + Reason.INVALID_GROUPNAME, "Invalid group")); + } + + protected User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { + return UsermgtTestUtils.createUser(aName, aPassword, aGroup); + } + + /** + * Constructs the admin, verify it contains no users and no groups. + */ + public void testConstruct() { + assertEquals(0, _admin.getUsers().size()); + assertEquals(0, _admin.getGroups().size()); + assertEquals(0, _admin.getUserCount()); + assertEquals(0, _admin.getGroupCount()); + } + + /** + * Creates a new group. Verifies the group is created correctly and that the + * user is added. + * + */ + public void testCreateGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + assertNotNull(group); + assertEquals(GROUP1, group.getName()); + + Set groups = _admin.getGroups(); + assertEquals(1, groups.size()); + assertEquals(1, _admin.getGroupCount()); + assertTrue(groups.contains(group)); + } + + private void createInvalidGroup(String aUsername) { + try { + _admin.createGroup(aUsername); + fail(); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.INVALID_GROUPNAME, e + .getReason()); + assertEquals(0, _admin.getGroupCount()); + } + } + + /** + * Creates a new group with an invalid name. Verifies that the appropriate + * exception is thrown. + * + * @throws UserMgtException + */ + public void testCreateInvalidGroupName() throws UserMgtException { + createInvalidGroup(""); + createInvalidGroup("0abc"); // should not start with digits + createInvalidGroup("a b"); // should not contain spaces + createInvalidGroup(" aa"); + createInvalidGroup("aa "); + } + + /** + * Creates a new group which conflicts with an existing one. Verifies that + * the UserMgtException is thrown and that no group is added. + * + */ + public void testCreateDuplicateGroup() throws UserMgtException { + _admin.createGroup(GROUP1); + try { + _admin.createGroup(GROUP1); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason()); + assertEquals(1, _admin.getGroupCount()); + return; + } + fail(); + } + + /** + * Creates a new user. Verifies the user is created correctly and that the + * user is added. + * + */ + public void testCreateUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + assertNotNull(user); + assertEquals(USER1, user.getName()); + user.checkPassword(PASS1); + + Set users = _admin.getUsers(); + assertEquals(1, users.size()); + assertEquals(1, _admin.getUserCount()); + assertTrue(users.contains(user)); + } + + private void createInvalidUser(String aUsername, Group aGroup) { + try { + _admin.createUser(aUsername, "pass", aGroup); + fail(); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.INVALID_USERNAME, e + .getReason()); + assertEquals(0, _admin.getUserCount()); + } + } + + /** + * Constructs users with invalid names. Verifies that the appropriate + * exception is thrown. + * + */ + public void testCreateInvalidUserName() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + createInvalidUser("", group); + createInvalidUser("0abc", group); // should not start with digits + createInvalidUser("a b", group); // should not contain spaces + createInvalidUser(" aa", group); + createInvalidUser("aa ", group); + } + + /** + * Creates a new user which conflicts with an existing one. Verifies that + * the UserMgtException is thrown and that no user is added. + * + */ + public void testCreateDuplicateUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + _admin.createUser(USER1, PASS1, group); + try { + _admin.createUser(USER1, PASS2, group); + fail(); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.DUPLICATE_USER, e.getReason()); + assertEquals(1, _admin.getUserCount()); + } + } + + /** + * Gets a known user by name. Verifies the correct user is obtained. + * Verifies that null is returned when trying to obtain an unknown user. + * + */ + public void testGetUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + User user2 = _admin.getUser(USER1); + assertTrue(user.equals(user2)); + assertNull(_admin.getUser(USER2)); + } + + /** + * Gets a known group by name. Verifies the correct group is obtained. + * Verifies that null is returned when the group is not known. + * + */ + public void testGetGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + Group group2 = _admin.getGroup(GROUP1); + assertTrue(group.equals(group2)); + assertNull(_admin.getGroup(GROUP2)); + } + + /** + * Adds a user to a group. Verifies that the user is added using several API + * calls. Verifies that an exception occurs if the user is not already part + * of the group. + * + */ + public void testAddUserToGroup() throws UserMgtException { + + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + Group group2 = _admin.createGroup(GROUP2); + assertTrue(user.isInGroup(group)); + assertFalse(user.isInGroup(group2)); + _admin.addUserToGroup(user, group2); + assertTrue(user.isInGroup(group)); + assertTrue(user.isInGroup(group2)); + Set users = _admin.getUsers(group2); + assertNotNull(users); + assertEquals(1, users.size()); + assertTrue(users.contains(user)); + + try { + _admin.addUserToGroup(user, group); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.USER_ALREADY_IN_GROUP, e + .getReason()); + return; + } + fail(); + } + + /** + * Adds a user to a group where the user does not exist. Verifies that an + * exception occurs. + * + */ + public void testAddUserToGroupUnknownUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = createUser(USER1, PASS1, group); + try { + _admin.addUserToGroup(user, group); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason()); + return; + } + fail(); + } + + /** + * Adds a user to a group where the user does not exist. Verifies that an + * exception occurs. + * + */ + public void testAddUserToGroupUnknownGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + Group group2 = new Group(GROUP2); + try { + _admin.addUserToGroup(user, group2); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason()); + return; + } + fail(); + } + + /** + * Removes a user from a group. Verifies that the user is removed from the + * group using several API calls. Verifies that an exception occurs if the + * user not part of the group or if the user is only part of one group. + */ + public void testRemoveUserFromGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + + User user = _admin.createUser(USER1, PASS1, group); + Group group2 = _admin.createGroup(GROUP2); + _admin.addUserToGroup(user, group2); + Set groups = user.getGroups(); + assertEquals(2, groups.size()); + assertTrue(groups.contains(group)); + assertTrue(groups.contains(group2)); + + _admin.removeUserFromGroup(user, group); + groups = user.getGroups(); + assertEquals(1, groups.size()); + assertTrue(groups.contains(group2)); + assertFalse(groups.contains(group)); + } + + /** + * Removes a user from a group where the user is not known. Verifies that an + * exception is thrown. + * + */ + public void testRemoveUserFromGroupUnknownUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = createUser(USER1, GROUP1, group); + try { + _admin.removeUserFromGroup(user, group); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason()); + } + } + + /** + * Removes a user from a group where the group is not known. Verifies that + * an exception is thrown. + * + */ + public void testRemoveUserFromGroupUnknownGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + Group group2 = new Group(GROUP2); + try { + _admin.removeUserFromGroup(user, group2); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason()); + } + } + + /** + * Removes a user from a group where the user is only part of one group. + * Verifies that an exception is thrown. + */ + public void testRemoveUserFromGroupOnlyGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + try { + _admin.removeUserFromGroup(user, group); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.USER_MUST_BE_IN_A_GROUP, e + .getReason()); + } + } + + /** + * Gets the list of users and groups. Verifies that the correct suers and + * groups are returned. Verifies also that the relations from user to group + * are correct. + * + */ + public void testGetUsersAndGroups() throws UserMgtException { + Group group1 = _admin.createGroup(GROUP1); + Group group2 = _admin.createGroup(GROUP2); + + User user1 = _admin.createUser(USER1, PASS1, group1); + _admin.addUserToGroup(user1, group2); + User user2 = _admin.createUser(USER2, PASS2, group2); + + Set users = _admin.getUsers(); + assertEquals(2, users.size()); + assertTrue(users.contains(user1)); + assertTrue(users.contains(user2)); + + Set groups = _admin.getGroups(); + assertEquals(2, groups.size()); + assertTrue(groups.contains(group1)); + assertTrue(groups.contains(group2)); + + assertTrue(user1.isInGroup(group1)); + assertTrue(user1.isInGroup(group2)); + assertFalse(user2.isInGroup(group1)); + assertTrue(user2.isInGroup(group2)); + + Set groups1 = user1.getGroups(); + assertEquals(2, groups1.size()); + + Set groups2 = user2.getGroups(); + assertEquals(1, groups2.size()); + } + + /** + * Renames a user. Verifies that the user is renamed. Verifies that + * exceptions are thrown when an attempt is made to rename the user to + * itself or to another existing user, or when the group does not exist. + * + */ + public void testRenameUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user1 = _admin.createUser(USER1, PASS1, group); + _admin.renameUser(user1, USER2); + assertEquals(USER2, user1.getName()); + assertEquals(user1, _admin.getUser(USER2)); + + _admin.createUser(USER1, PASS1, group); + + try { + _admin.renameUser(user1, USER1); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.DUPLICATE_USER, e.getReason()); + + // do a trivial reanem + try { + _admin.renameUser(user1, user1.getName()); + } catch (UserMgtException e2) { + assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2 + .getReason()); + return; + } + fail(); + } + fail(); + } + + /** + * Renames a user to a user with an invalid username. Verifies that the + * appropriate exception is thrown. + * + */ + public void testRenameUserInvalidUsername() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user1 = _admin.createUser(USER1, PASS1, group); + try { + _admin.renameUser(user1, USER2); + } catch (UserMgtException e) { + assertEquals(e.getReason(), Reason.INVALID_USERNAME); + } + } + + /** + * Renames a group. Verifies that the group is renamed. Verifies that + * exceptions are thrown when an attempt is made to rename the group to + * itself or to another existing group or when the group does not exist. + * + */ + public void testRenameGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + _admin.renameGroup(group, GROUP2); + assertEquals(GROUP2, group.getName()); + assertEquals(group, _admin.getGroup(GROUP2)); + + _admin.createGroup(GROUP1); + try { + _admin.renameGroup(group, GROUP1); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.DUPLICATE_GROUP, e.getReason()); + + // do a trivial reanem + try { + _admin.renameGroup(group, group.getName()); + } catch (UserMgtException e2) { + assertEquals(UserMgtException.Reason.TRIVIAL_RENAME, e2 + .getReason()); + return; + } + fail(); + return; + } + fail(); + } + + /** + * Renames a group to a group with an invalid name. Verifies that the + * appropriate exception is thrown. + * + */ + public void testRenameGroupInvalidGroupname() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + try { + _admin.renameGroup(group, "a b"); + } catch (UserMgtException e) { + assertEquals(e.getReason(), Reason.INVALID_GROUPNAME); + } + } + + /** + * Removes a user. Verifies that the user is removed. Verifies that the an + * exception is thrown when the user does not exist. + * + */ + public void testRemoveUser() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + + assertEquals(1, _admin.getUserCount()); + _admin.removeUser(user); + assertEquals(0, _admin.getUserCount()); + + _admin.createUser(USER1, PASS1, group); + assertEquals(1, _admin.getUserCount()); + + User user2 = createUser(USER2, PASS2, group); + + try { + _admin.removeUser(user2); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.UNKNOWN_USER, e.getReason()); + } + } + + /** + * Removes a group. Verifies that the group is removed. Verifies that the an + * exception is thrown when the group does not exist or if there are still + * users in the group. + * + */ + public void testRemoveGroup() throws UserMgtException { + Group group1 = _admin.createGroup(GROUP1); + assertEquals(1, _admin.getGroupCount()); + _admin.removeGroup(group1); + assertEquals(0, _admin.getGroupCount()); + group1 = _admin.createGroup(GROUP1); + + _admin.createUser(USER1, PASS1, group1); + try { + _admin.removeGroup(group1); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.GROUP_STILL_OCCUPIED, e + .getReason()); + return; + } + fail(); + } + + /** + * Tries to remove an unknown group. Verifies that an exception is thrown. + * + */ + public void testRemoveGroupUnknownGroup() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + Group group2 = new Group(GROUP2); + try { + _admin.removeGroup(group2); + } catch (UserMgtException e) { + assertEquals(UserMgtException.Reason.UNKNOWN_GROUP, e.getReason()); + } + } + + /** + * Changes the password, verifies that this succeeds. + * + * @throws UserMgtException + */ + public void testChangePassword() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + User user = _admin.createUser(USER1, PASS1, group); + user.changePassword(PASS1, PASS2); + + // retrieve the user and verifies the password hasn't changed. + User user2 = _admin.getUser(USER1); + try { + user2.checkPassword(PASS2); + fail(); // password should not have changed already. + } catch (UserMgtException e) { + // ok. + } + + // now notify the admin of the change in the user + _admin.userModified(user); + + user2 = _admin.getUser(USER1); + user2.checkPassword(PASS2); // this time it should succeed. + + } + + /** + * Performance test. Finds a user by name. + * + */ + public void testPerformanceFindUserByName() throws UserMgtException { + Group group = _admin.createGroup(GROUP1); + _admin.createUser(USER1, PASS1, group); + + int n = 1000; + long time = System.currentTimeMillis(); + for (int i = 0; i < n; i++) { + _admin.getUser(USER1); + } + LOGGER.info("Looked up a user " + n + " times in " + + (float) (System.currentTimeMillis() - time) / 1000.0); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java new file mode 100644 index 00000000..07a376c5 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/UsermgtTestUtils.java @@ -0,0 +1,62 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt; + +import org.wamblee.security.encryption.Md5HexMessageDigester; +import org.wamblee.usermgt.UserMgtException.Reason; + +/** + * User management test utilities. + * + * @author Erik Brakkee + */ +public class UsermgtTestUtils { + + private static final String DUMMY_GROUP = "dummygroup"; + private static final String DUMMY_PASSWD = "dummypasswd"; + + public static Group createGroup(String aName) { + return new Group(aName); + } + + public static User createUser(String aUsername) throws UserMgtException { + return createUser(aUsername, DUMMY_GROUP); + } + + public static User createUser(String aUsername, String aGroup) throws UserMgtException { + return createUser(aUsername, createGroup(aGroup)); + } + + public static User createUser(String aUsername, Group aGroup) throws UserMgtException { + return createUser(aUsername, DUMMY_PASSWD, aGroup); + } + + public static User createUser(String aName, String aPassword, Group aGroup) throws UserMgtException { + return new User(aName, aPassword, aGroup, + new RegexpNameValidator(RegexpNameValidator.PASSWORD_PATTERN, + Reason.INVALID_PASSWORD, "Password must be at least 6 chars"), + new Md5HexMessageDigester()); + } + + public static void addUserToGroup(User aUser, Group aGroup) throws UserMgtException { + aUser.addGroup(aGroup); + } + + public static void removeUserFromGroup(User aUser, Group aGroup) throws UserMgtException { + aUser.removeGroup(aGroup); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java new file mode 100644 index 00000000..fa80b1a4 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateGroupSetTest.java @@ -0,0 +1,132 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt.hibernate; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.component.DatabaseTesterComponent; +import org.wamblee.test.spring.TestTransactionCallback; +import org.wamblee.usermgt.GroupSet; +import org.wamblee.usermgt.InMemoryGroupSetTest; + +/** + * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet} + * + * @author Erik Brakkee + */ +public class HibernateGroupSetTest extends InMemoryGroupSetTest { + + private static final String GROUP_TABLE = "GROUPS"; + + private static final String GROUP_QUERY = "select * from " + GROUP_TABLE + " where name = ?"; + + private DefaultContainer _container; + private Scope _scope; + + private DatabaseTesterComponent _databaseTester; + private GroupSet _groupSet; + + @Override + protected void setUp() throws Exception { + + _container = new UserMgtRepositoryTestContainer("top"); + + ObjectConfiguration config = new ObjectConfiguration( + HibernateGroupSetTest.class); + config.getSetterConfig().clear().add( + "setGroupSet").add("setDatabaseTester"); + _container.addComponent("testcase", this, config); + + _scope = _container.start(); + + _databaseTester.cleanDatabase(); + super.setUp(); + } + + @Override + protected void tearDown() throws Exception { + _container.stop(_scope); + super.tearDown(); + } + + public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { + _databaseTester = aDatabaseTester; + } + + public void setGroupSet(GroupSet aGroupSet) { + _groupSet = aGroupSet; + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int) + */ + @Override + protected void checkGroupCount(int aSize) throws SQLException { + _databaseTester.flush(); + super.checkGroupCount(aSize); + assertEquals(aSize, _databaseTester.getTableSize(GROUP_TABLE)); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String) + */ + @Override + protected void checkGroupExists(final String aGroup) throws SQLException { + _databaseTester.flush(); + Map 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) + */ + @Override + protected void checkGroupNotExists(String aGroup) throws SQLException { + _databaseTester.flush(); + ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup); + assertEquals(0, _databaseTester.countResultSet(result)); + } + + /* (non-Javadoc) + * @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet() + */ + @Override + protected GroupSet createGroupSet() { + return _groupSet; + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java new file mode 100644 index 00000000..f707dba0 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserAdministrationTest.java @@ -0,0 +1,146 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt.hibernate; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.sql.SQLException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wamblee.cache.EhCache; +import org.wamblee.system.adapters.ClassConfiguration; +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.components.DatabaseComponentFactory; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.component.DatabaseTesterComponent; +import org.wamblee.system.spring.component.DatasourceComponent; +import org.wamblee.test.spring.TestTransactionCallbackWithoutResult; +import org.wamblee.usermgt.UserAdministration; +import org.wamblee.usermgt.UserAdministrationImplTest; + +/** + * User administration tests with persistence based on Hibernate. This executes + * the same test cases as {@link org.wamblee.usermgt.UserAdministrationImplTest} + * with in addition, one test case that executes all Hibernate test cases + * separately with each test case in its own transaction. + * + * @author Erik Brakkee + */ +public class HibernateUserAdministrationTest extends UserAdministrationImplTest { + + private static final Log LOG = LogFactory.getLog(HibernateUserAdministrationTest.class); + + private DefaultContainer _container; + private Scope _scope; + + private DatabaseTesterComponent _databaseTester; + private EhCache _userCache; + private UserAdministration _userAdmin; + + + /* (non-Javadoc) + * @see org.wamblee.usermgt.UserAdministrationImplTest#setUp() + */ + @Override + protected void setUp() throws Exception { + + _container = new DefaultContainer("top"); + DatabaseComponentFactory.addDatabaseConfig(_container); + _container.addComponent(new DatasourceComponent("datasource")); + _container.addComponent(new UserAdministrationComponent("admin", true)); + + ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class); + dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters(); + _container.addComponent("databaseTester", dbtesterConfig); + + ObjectConfiguration config = new ObjectConfiguration( + HibernateUserAdministrationTest.class); + config.getSetterConfig().clear().add( + "setUserCache").add("setDatabaseTester").add("setUserAdmin"); + _container.addComponent("testcase", this, config); + + _scope = _container.start(); + + _databaseTester.cleanDatabase(); + + super.setUp(); + clearUserCache(); + } + + public void setUserCache(EhCache aUserCache) { + _userCache = aUserCache; + } + + public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { + _databaseTester = aDatabaseTester; + } + + public void setUserAdmin(UserAdministration aUserAdmin) { + _userAdmin = aUserAdmin; + } + + @Override + protected void tearDown() throws Exception { + _container.stop(_scope); + super.tearDown(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.UserAdministrationImplTest#createAdmin() + */ + @Override + protected UserAdministration createAdmin() { + return _userAdmin; + } + + public void testAllTestsInASeparateTransaction() throws SQLException { + + Method[] methods = UserAdministrationImplTest.class.getMethods(); + for (final Method method : methods) { + if (method.getName().startsWith("test")) { + _databaseTester.cleanDatabase(); + clearUserCache(); + _databaseTester.executeTransaction(new TestTransactionCallbackWithoutResult() { + public void execute() throws Exception { + LOG.info("Running test " + method.getName()); + try { + method.invoke(HibernateUserAdministrationTest.this); + } catch (Throwable t) { + LOG.error("Test " + method.getName() + " failed"); + throw new RuntimeException(t.getMessage(), t); + } + finally { + LOG.info("Test " + method.getName() + " finished"); + } + + } + }); + } + } + } + + /** + * + */ + private void clearUserCache() { + _userCache.clear(); + } +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java new file mode 100644 index 00000000..82588b3b --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/HibernateUserSetTest.java @@ -0,0 +1,243 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.usermgt.hibernate; + +import java.io.Serializable; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Set; + +import org.wamblee.cache.EhCache; +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.component.DatabaseTesterComponent; +import org.wamblee.usermgt.Group; +import org.wamblee.usermgt.GroupSet; +import org.wamblee.usermgt.InMemoryUserSetTest; +import org.wamblee.usermgt.User; +import org.wamblee.usermgt.UserMgtException; +import org.wamblee.usermgt.UserSet; + +/** + * Tests for {@link org.wamblee.usermgt.hibernate.HibernateGroupSet} + * + * @author Erik Brakkee + */ +public class HibernateUserSetTest extends InMemoryUserSetTest { + + private static final String USER_TABLE = "USERS"; + private static final String GROUP_TABLE = "GROUPS"; + + private static final String USER_QUERY = "select * from " + USER_TABLE + + " where name = ?"; + private static final String GROUP_QUERY = "select * from " + GROUP_TABLE + + " where name = ?"; + + private DefaultContainer _container; + private Scope _scope; + + private UserSet _userset; + private GroupSet _groupset; + private EhCache _userCache; + private DatabaseTesterComponent _databaseTester; + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryUserSetTest#setUp() + */ + @Override + protected void setUp() throws Exception { + + _container = new UserMgtRepositoryTestContainer("top"); + + ObjectConfiguration config = new ObjectConfiguration( + HibernateUserSetTest.class); + config.getSetterConfig().clear().add("setUserset").add( + "setGroupset").add("setDatabaseTester").add("setUserCache"); + _container.addComponent("testcase", this, config); + + _scope = _container.start(); + + clearUserCache(); + _databaseTester.cleanDatabase(); + + super.setUp(); + } + + public void setUserset(UserSet aUserset) { + _userset = aUserset; + } + + public void setGroupset(GroupSet aGroupset) { + _groupset = aGroupset; + } + + public void setUserCache(EhCache aUserCache) { + _userCache = aUserCache; + } + + public void setDatabaseTester(DatabaseTesterComponent aDatabaseTester) { + _databaseTester = aDatabaseTester; + } + + @Override + protected void tearDown() throws Exception { + _container.stop(_scope); + super.tearDown(); + } + + /** + * Clears the user cache. + */ + private void clearUserCache() { + _userCache.clear(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int) + */ + @Override + protected void checkUserCount(int aSize) throws SQLException { + _databaseTester.flush(); + super.checkUserCount(aSize); + assertEquals(aSize, _databaseTester.getTableSize(USER_TABLE)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String) + */ + @Override + protected void checkUserExists(String aUser) throws SQLException { + _databaseTester.flush(); + ResultSet result = _databaseTester.executeQuery(USER_QUERY, aUser); + assertEquals(1, _databaseTester.countResultSet(result)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String) + */ + @Override + protected void checkUserNotExists(String aUser) throws SQLException { + _databaseTester.flush(); + ResultSet result = _databaseTester.executeQuery(USER_QUERY, aUser); + assertEquals(0, _databaseTester.countResultSet(result)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupCount(int) + */ + @Override + protected void checkGroupCount(int aSize) throws SQLException { + _databaseTester.flush(); + assertEquals(aSize, _databaseTester.getTableSize(GROUP_TABLE)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupExists(java.lang.String) + */ + @Override + protected void checkGroupExists(String aGroup) throws SQLException { + _databaseTester.flush(); + + ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup); + assertEquals(1, _databaseTester.countResultSet(result)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#checkGroupNotExists(java.lang.String) + */ + @Override + protected void checkGroupNotExists(String aGroup) throws SQLException { + _databaseTester.flush(); + ResultSet result = _databaseTester.executeQuery(GROUP_QUERY, aGroup); + assertEquals(0, _databaseTester.countResultSet(result)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryGroupSetTest#createGroupSet() + */ + @Override + protected UserSet createUserSet() { + return _userset; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.usermgt.InMemoryUserSetTest#createGroupSet() + */ + @Override + protected GroupSet createGroupSet() { + return _groupset; + } + + /** + * Reproduction of a bug. Create a user which is in group1 Add it to a + * second group group2. Remove the user from group1. Verify the user is in + * group2. + */ + public void testVerifyAddRemove() throws SQLException, UserMgtException { + _databaseTester.cleanDatabase(); // just to be sure. + GroupSet groups = getGroups(); + assertEquals(0, groups.size()); + Group group1 = createGroup("group1"); + Group group2 = createGroup("group2"); + groups.add(group1); + groups.add(group2); + checkGroupExists("group1"); + checkGroupExists("group2"); + + User user = createUser("user", PASSWORD, group1); + getUsers().add(user); + checkUserExists("user"); + + addUserToGroup(user, group2); + getUsers().userModified(user); + clearUserCache(); + User user2 = getUsers().find("user"); + Set userGroups = user2.getGroups(); + assertTrue(user2.isInGroup("group1")); + assertTrue(user2.isInGroup("group2")); + assertEquals(2, userGroups.size()); + + removeUserFromGroup(user, group1); + getUsers().userModified(user); + clearUserCache(); + user2 = getUsers().find("user"); + userGroups = user2.getGroups(); + assertFalse(user2.isInGroup("group1")); + assertTrue(user2.isInGroup("group2")); + assertEquals(1, userGroups.size()); + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java new file mode 100644 index 00000000..dd443916 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/java/org/wamblee/usermgt/hibernate/UserMgtRepositoryTestContainer.java @@ -0,0 +1,53 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.usermgt.hibernate; + +import java.io.IOException; + +import org.wamblee.system.adapters.ClassConfiguration; +import org.wamblee.system.adapters.DefaultContainer; +import org.wamblee.system.adapters.ObjectConfiguration; +import org.wamblee.system.components.DatabaseComponentFactory; +import org.wamblee.system.spring.component.DatabaseTesterComponent; +import org.wamblee.system.spring.component.DatasourceComponent; +import org.wamblee.system.spring.component.HibernateComponent; +import org.wamblee.usermgt.UserGroupRepositoryComponent; + +/** + * + * Test container for repository tests of user management. + * + * @author Erik Brakkee + */ +public class UserMgtRepositoryTestContainer extends DefaultContainer { + + public UserMgtRepositoryTestContainer(String aName) throws IOException { + super(aName); + DatabaseComponentFactory.addDatabaseConfig(this); + addComponent(new DatasourceComponent("datasource")); + + ObjectConfiguration mappingFilesConfig = new ObjectConfiguration(UsermgtHibernateMappingFiles.class); + mappingFilesConfig.getSetterConfig().initAllSetters(); + addComponent("mappingFiles", new UsermgtHibernateMappingFiles(), mappingFilesConfig); + addComponent(new HibernateComponent("hibernate")); + addComponent(new UserGroupRepositoryComponent("usersgroups")); + ClassConfiguration dbtesterConfig = new ClassConfiguration(DatabaseTesterComponent.class); + dbtesterConfig.getObjectConfig().getSetterConfig().initAllSetters(); + addComponent("databaseTester", dbtesterConfig); + + } + +} diff --git a/tags/wamblee-utils-0.2/security/src/test/resources/properties/test.org.wamblee.security.database.properties b/tags/wamblee-utils-0.2/security/src/test/resources/properties/test.org.wamblee.security.database.properties new file mode 100644 index 00000000..bff2ee47 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/resources/properties/test.org.wamblee.security.database.properties @@ -0,0 +1,11 @@ + + +# Database properties for test runs in a J2SE environment. + +# See ORMappingConfig.DatabaseType for allowed values +database.type=MYSQL_INNO_DB + +database.driver=com.mysql.jdbc.Driver +database.url=jdbc:mysql://localhost:3306/test +database.username=erik +database.password=abc123 \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/test/resources/properties/test.org.wamblee.security.usermgt.properties b/tags/wamblee-utils-0.2/security/src/test/resources/properties/test.org.wamblee.security.usermgt.properties new file mode 100644 index 00000000..aa84735d --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/resources/properties/test.org.wamblee.security.usermgt.properties @@ -0,0 +1,5 @@ + +############################################################################## +# Name of the administrators group +############################################################################## +org.wamblee.security.admingroup=administrators diff --git a/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.datasource.xml b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.datasource.xml new file mode 100644 index 00000000..d7183342 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.datasource.xml @@ -0,0 +1,25 @@ + + + + + + + + ${database.url} + + + ${database.username} + + + ${database.password} + + + diff --git a/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.properties.xml b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.properties.xml new file mode 100644 index 00000000..5fa2f72b --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.properties.xml @@ -0,0 +1,16 @@ + + + + + + + + + properties/test.org.wamblee.security.hibernate.properties + properties/test.org.wamblee.security.usermgt.properties + properties/test.org.wamblee.security.database.properties + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.useraccessor.xml b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.useraccessor.xml new file mode 100644 index 00000000..e306d63a --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.useraccessor.xml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.usermgtinitializer.xml b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.usermgtinitializer.xml new file mode 100644 index 00000000..54c9f360 --- /dev/null +++ b/tags/wamblee-utils-0.2/security/src/test/resources/spring/test.org.wamblee.security.usermgtinitializer.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + erik + admin + + + + + + users + ${org.wamblee.security.admingroup} + + + + + + abc123 + abc123 + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/support/general/pom.xml b/tags/wamblee-utils-0.2/support/general/pom.xml new file mode 100644 index 00000000..fcc6d2a9 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/pom.xml @@ -0,0 +1,62 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-support-general + jar + /support/general + http://wamblee.org + + + oro + oro + + + commons-logging + commons-logging + + + org.apache.derby + derby + test + + + org.apache.derby + derbyclient + test + + + org.apache.derby + derbynet + test + + + commons-beanutils + commons-beanutils + + + + log4j + log4j + + + dom4j + dom4j + + + net.sf.ehcache + ehcache + + + jaxen + jaxen + + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/Cache.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/Cache.java new file mode 100644 index 00000000..15f2c508 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/Cache.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.cache; + +import java.io.Serializable; + +/** + * The 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. + */ +public interface Cache { + + /** + * Adds a key-value pair to the cache. + * @param aKey Key. + * @param aValue Value. + */ + void put(KeyType aKey, ValueType aValue); + + /** + * Retrieves a value from the cache. + * @param aKey Key to retrieve. + * @return Key. + */ + ValueType get(KeyType aKey); + + /** + * Removes an entry from the cache. + * @param aKey Key to remove the entry for. + */ + void remove(KeyType aKey); + + /** + * Removes all entries from the cache. + * + */ + void clear(); +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/CachedObject.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/CachedObject.java new file mode 100644 index 00000000..58daf8c9 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/CachedObject.java @@ -0,0 +1,131 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.cache; + +import java.io.Serializable; + +import org.apache.log4j.Logger; + +/** + * Represents a cached object. The object is either retrieved from the cache if + * the cache has it, or a call back is invoked to get the object (and put it in + * the cache). + * + * @author Erik Brakkee + */ +public class CachedObject { + + 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 + */ + 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); + } + + /** + * Cache to use. + */ + private Cache _cache; + + /** + * Key of the object in the cache. + */ + private KeyType _objectKey; + + /** + * Computation used to obtain the object if it is not found in the cache. + */ + private Computation _computation; + + /** + * Constructs the cached object. + * + * @param aCache + * Cache to use. + * @param aObjectKey + * Key of the object in the cache. + * @param aComputation + * Computation to get the object in case the object is not in the + * cache. + */ + public CachedObject(Cache aCache, KeyType aObjectKey, + 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. + * + * @return Object. + */ + public ValueType get() { + ValueType object = (ValueType) _cache.get(_objectKey); // the used + // cache is + // thread safe. + if (object == null) { + // synchronize the computation to make sure that the object is only + // computed + // once when multiple concurrent threads detect that the entry must + // be + // recomputed. + synchronized (this) { + object = (ValueType) _cache.get(_objectKey); + if (object == null) { + // No other thread did a recomputation so we must do this + // now. + LOGGER.debug("Refreshing cache for '" + _objectKey + "'"); + object = _computation.getObject(_objectKey); + _cache.put(_objectKey, object); + } + } + } + return object; + } + + /** + * Invalidates the cache for the object so that it is recomputed the next + * time it is requested. + * + */ + public void invalidate() { + _cache.remove(_objectKey); + } + + /** + * Gets the cache. + * + * @return Cache. + */ + public Cache getCache() { + return _cache; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/EhCache.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/EhCache.java new file mode 100644 index 00000000..6a631866 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/EhCache.java @@ -0,0 +1,124 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.cache; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheException; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; + +import org.apache.log4j.Logger; +import org.wamblee.io.InputResource; + +/** + * Cache implemented on top of EhCache. + * + * @author Erik Brakkee + */ +public class EhCache + implements org.wamblee.cache.Cache { + + private static final Logger LOGGER = Logger.getLogger(EhCache.class); + + /** + * EH Cache manager. + */ + private CacheManager _manager; + + /** + * EH cache. + */ + private Cache _cache; + + /** + * Constructs a cache based on EHCache. + * + * @param aResource + * Resource containing the configuration file for EHCache. + * @param aCacheName + * Name of the cache to use. If a cache with this name does not + * exist, one is created based on default settings. + * @throws IOException + * @throws CacheException + */ + public EhCache(InputResource aResource, String aCacheName) + throws IOException, CacheException { + InputStream is = aResource.getInputStream(); + try { + _manager = new CacheManager(is); + _cache = _manager.getCache(aCacheName); + if (_cache == null) { + LOGGER.warn("Creating cache '" + aCacheName + + "' because it is not configured"); + _manager.addCache(aCacheName); + _cache = _manager.getCache(aCacheName); + } + assert _cache != null; + } finally { + is.close(); + } + + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#put(KeyType, ValueType) + */ + public void put(KeyType aKey, ValueType aValue) { + _cache.put(new Element(aKey, aValue)); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#get(KeyType) + */ + public ValueType get(KeyType aKey) { + try { + Element element = _cache.get(aKey); + if (element == null) { + return null; + } + return (ValueType) element.getValue(); + } catch (CacheException e) { + throw new RuntimeException("Cache problem key = '" + aKey + "'", e); + } + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#remove(KeyType) + */ + public void remove(KeyType aKey) { + _cache.remove(aKey); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#clear() + */ + public void clear() { + _cache.removeAll(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/ForeverCache.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/ForeverCache.java new file mode 100644 index 00000000..8b7f8bf4 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/ForeverCache.java @@ -0,0 +1,79 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.cache; + +import java.io.Serializable; +import java.util.HashMap; + +/** + * A very simple cache based on a HashMap, It never expires any entries, and has + * no bounds on its size. + * + * @author Erik Brakkee + */ +public class ForeverCache + implements Cache { + + /** + * Cached entries. + */ + private HashMap _map; + + /** + * Constructs the cache. + * + */ + public ForeverCache() { + _map = new HashMap(); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#put(KeyType, ValueType) + */ + public synchronized void put(KeyType aKey, ValueType aValue) { + _map.put(aKey, aValue); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#get(KeyType) + */ + public synchronized ValueType get(KeyType aKey) { + return _map.get(aKey); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#remove(KeyType) + */ + public synchronized void remove(KeyType aKey) { + _map.remove(aKey); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.cache.Cache#clear() + */ + public synchronized void clear() { + _map.clear(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/ZeroCache.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/ZeroCache.java new file mode 100644 index 00000000..55f9cc95 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/ZeroCache.java @@ -0,0 +1,62 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.cache; + +import java.io.Serializable; + +/** + * A cache that does not cache. This implementation is useful for disabling caching. + * Because of this implementation, application code does not need to distinguish + * between the situation where it a cache is used and where it isn't. + * + * @author Erik Brakkee + */ +public class ZeroCache + implements Cache { + + public ZeroCache() { + // Empty. + } + + /* (non-Javadoc) + * @see org.wamblee.cache.Cache#put(KeyType, ValueType) + */ + public void put(KeyType aKey, ValueType aValue) { + // Empty. + } + + /* (non-Javadoc) + * @see org.wamblee.cache.Cache#get(KeyType) + */ + public ValueType get(KeyType aKey) { + return null; + } + + /* (non-Javadoc) + * @see org.wamblee.cache.Cache#remove(KeyType) + */ + public void remove(KeyType aKey) { + // Empty + } + + /* (non-Javadoc) + * @see org.wamblee.cache.Cache#clear() + */ + public void clear() { + // Empty + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/package.html new file mode 100644 index 00000000..17bde142 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/cache/package.html @@ -0,0 +1,16 @@ + + + + wamblee.org + + + +This package provides an interface for a cache together with several +implementations. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java new file mode 100644 index 00000000..75cdcb1e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/collections/CollectionFilter.java @@ -0,0 +1,40 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.collections; + +import java.util.Collection; + +import org.wamblee.conditions.Condition; + +public class CollectionFilter { + + /** + * Filters a collection by adding all elements in the from collection + * that satisfy a given condition to the to collection. + * @param 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); + } + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java new file mode 100644 index 00000000..2fe0d11f --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/JvmLock.java @@ -0,0 +1,53 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.concurrency; + +import java.util.concurrent.locks.ReentrantLock; + +/** + * In memory JVM lock. + * + * @author Erik Brakkee + */ +public class JvmLock implements Lock { + + /** + * Reentrant lock to use. + */ + private ReentrantLock _lock; + + /** + * In-memory lock. + */ + public JvmLock() { + _lock = new ReentrantLock(true); + } + + /* (non-Javadoc) + * @see org.wamblee.concurrency.Lock#acquire() + */ + public void acquire() { + _lock.lock(); + } + + /* (non-Javadoc) + * @see org.wamblee.concurrency.Lock#release() + */ + public void release() { + _lock.unlock(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/Lock.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/Lock.java new file mode 100644 index 00000000..50cc7842 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/Lock.java @@ -0,0 +1,37 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.concurrency; + +/** + * Represents a re-entrant lock. + * Implementations can provide inmemory JVM locking or full cluster safe locking + * mechanisms. + * + * @author Erik Brakkee + */ +public interface Lock { + + /** + * Acquires the lock. + */ + void acquire(); + + /** + * Releases the lock. + */ + void release(); +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java new file mode 100644 index 00000000..e7658161 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/ReadWriteLock.java @@ -0,0 +1,149 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.concurrency; + +import java.util.HashSet; + + +/** + * Read-write lock for allowing multiple concurrent readers or at most one + * writer. This implementation does not aim for high performance but for + * robustness and simplicity. Users of this class should not synchronize on + * objects of this class. + */ +public class ReadWriteLock { + /** + * Sets containing the references to the threads that are currently + * reading. This administration is useful to check that the lock has + * already been acquired before it is release. This check adds robustness + * to the application. + */ + private HashSet _readers; + + /** + * The thread that has acquired the lock for writing or null if no such + * thread exists currently. + */ + private Thread _writer; + + /** + * Constructs read-write lock. + */ + public ReadWriteLock() { + _readers = new HashSet(); + _writer = null; + } + + /** + * Acquires the lock for reading. This call will block until the lock can + * be acquired. + * + * @throws IllegalStateException Thrown if the read or write lock is + * already acquired. + */ + public synchronized void acquireRead() { + if (_readers.contains(Thread.currentThread())) { + throw new IllegalStateException( + "Read lock already acquired by current thread: " + + Thread.currentThread()); + } + + if (_writer == Thread.currentThread()) { + throw new IllegalStateException( + "Trying to acquire the read lock while already holding a write lock: " + + Thread.currentThread()); + } + + while (_writer != null) { + try { + wait(); + } catch (InterruptedException e) { + notifyAll(); + } + } + + _readers.add(Thread.currentThread()); + } + + /** + * Releases the lock for reading. Note: This implementation assumes that + * the lock has already been acquired for reading previously. + * + * @throws IllegalStateException Thrown when the lock was not acquired by + * this thread. + */ + public synchronized void releaseRead() { + if (!_readers.remove(Thread.currentThread())) { + throw new IllegalStateException( + "Cannot release read lock because current thread has not acquired it."); + } + + if (_readers.size() == 0) { + notifyAll(); + } + } + + /** + * Acquires the lock for writing. This call will block until the lock has + * been acquired. + * + * @throws IllegalStateException Thrown if the read or write lock is + * already acquired. + */ + public synchronized void acquireWrite() { + if (_writer == Thread.currentThread()) { + throw new IllegalStateException( + "Trying to acquire a write lock while already holding the write lock: " + + Thread.currentThread()); + } + + if (_readers.contains(Thread.currentThread())) { + throw new IllegalStateException( + "Trying to acquire a write lock while already holding the read lock: " + + Thread.currentThread()); + } + + // wait until there are no more writers and no more + // readers + while ((_writer != null) || (_readers.size() > 0)) { + try { + wait(); + } catch (InterruptedException e) { + notifyAll(); + } + } + + _writer = Thread.currentThread(); + + // notification not necessary since all writers and + // readers are now blocked by this thread. + } + + /** + * Releases the lock for writing. + * + * @throws IllegalStateException Thrown when the lock was not acquired. + */ + public synchronized void releaseWrite() { + if (_writer != Thread.currentThread()) { + throw new IllegalStateException( + "Cannot release write lock because it was not acquired. "); + } + + _writer = null; + notifyAll(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/package.html new file mode 100644 index 00000000..405a12a1 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/concurrency/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides utilities for dealing with concurrency. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/AndCondition.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/AndCondition.java new file mode 100644 index 00000000..50898739 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/AndCondition.java @@ -0,0 +1,69 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a logical and of different boolean conditions. + * + * @author Erik Brakkee + */ +public class AndCondition implements Condition { + + private List> _conditions; + + /** + * Constructs the condition. + * + * @param aCondition1 + * First condition. + * @param aCondition2 + * Second condition. + */ + public AndCondition(Condition aCondition1, Condition aCondition2) { + _conditions = new ArrayList>(); + _conditions.add(aCondition1); + _conditions.add(aCondition2); + } + + /** + * Constructs the and condition. + * + * @param aConditions + * List of conditions to use in the logical and. + */ + public AndCondition(List> aConditions) { + _conditions = aConditions; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program) + */ + public boolean matches(T aObject) { + for (Condition condition : _conditions) { + if (!condition.matches(aObject)) { + return false; + } + } + return true; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/Condition.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/Condition.java new file mode 100644 index 00000000..bf4c217a --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/Condition.java @@ -0,0 +1,33 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + + +/** + * Determines if an object matches a certain condition. + * + * @author Erik Brakkee + */ +public interface Condition { + + /** + * Determines if an object matches a condition. + * @param aObject object to match. + * @return True iff the object matches. + */ + boolean matches(T aObject); +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java new file mode 100644 index 00000000..eff83b1b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/FixedCondition.java @@ -0,0 +1,43 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +/** + * Condition which always returns a fixed value. + * + * @author Erik Brakkee + */ +public class FixedCondition implements Condition { + + private boolean _value; + + /** + * Constructs the condition. + * @param aValue Fixed value of the condition. + */ + public FixedCondition(boolean aValue) { + _value = aValue; + } + + /* (non-Javadoc) + * @see org.wamblee.conditions.Condition#matches(T) + */ + public boolean matches(T aObject) { + return _value; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/OrCondition.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/OrCondition.java new file mode 100644 index 00000000..0840c78b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/OrCondition.java @@ -0,0 +1,69 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a logical or of different boolean conditions. + * + * @author Erik Brakkee + */ +public class OrCondition implements Condition { + + private List> _conditions; + + /** + * Constructs the condition. + * + * @param aCondition1 + * First condition. + * @param aCondition2 + * Second condition. + */ + public OrCondition(Condition aCondition1, Condition aCondition2) { + _conditions = new ArrayList>(); + _conditions.add(aCondition1); + _conditions.add(aCondition2); + } + + /** + * Constructs the or condition. + * + * @param aConditions + * List of conditions to use in the logical or. + */ + public OrCondition(List> aConditions) { + _conditions = aConditions; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.crawler.kiss.ProgramMatcher#matches(org.wamblee.crawler.kiss.Program) + */ + public boolean matches(T aObject) { + for (Condition condition : _conditions) { + if (condition.matches(aObject)) { + return true; + } + } + return false; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java new file mode 100644 index 00000000..2ce7a0e9 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/PropertyRegexCondition.java @@ -0,0 +1,79 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +import java.lang.reflect.InvocationTargetException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.beanutils.PropertyUtils; + +/** + * Condition to check whether a given property value matches a certain + * regular expression. + * + * @author Erik Brakkee + */ +public class PropertyRegexCondition implements Condition { + + /** + * Property name. + */ + private String _property; + + /** + * Regular expression. + */ + private Pattern _regex; + + /** + * Whether or not to convert the value to lowercase before matching. + */ + private boolean _tolower; + + /** + * Constructs the condition. + * @param aProperty Name of the property to examine. + * @param aRegex Regular expression to use. + * @param aTolower Whether or not to convert the value to lowercase before matching. + */ + public PropertyRegexCondition(String aProperty, String aRegex, boolean aTolower) { + _property = aProperty; + _regex = Pattern.compile(aRegex); + _tolower = aTolower; + } + + /* (non-Javadoc) + * @see org.wamblee.conditions.Condition#matches(T) + */ + public boolean matches(T aObject) { + try { + String value = PropertyUtils.getProperty(aObject, _property) + ""; + if ( _tolower ) { + value = value.toLowerCase(); + } + Matcher matcher = _regex.matcher(value); + return matcher.matches(); + } catch (IllegalAccessException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (InvocationTargetException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e.getMessage(), e); + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/package.html new file mode 100644 index 00000000..3d489d60 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/conditions/package.html @@ -0,0 +1,16 @@ + + + + wamblee.org + + + +This package provides some basic support classes for checking boolean conditions +on objects. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanFactory.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanFactory.java new file mode 100644 index 00000000..56844bd7 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanFactory.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.general; + +/** + * Bean factory used to obtain objects in a transparent way. + * + * @author Erik Brakkee + */ +public interface BeanFactory { + + /** + * Finds a bean based on id. + * @param aId Id of the bean. + * @return Object (always non-null). + * @throws BeanFactoryException In case the object could not be found. + */ + Object find(String aId); + + /** + * Finds a bean of the given class and which can be cast to the + * specified class. This is typically used by specifying the interface + * class for retrieving an implementation of that class. This + * means that the bean implementing the class is configured in the bean factory + * with id equal to the class name of the interface. + * @param aClass Class of the object to find. + * @return Object (always non-null). + * @throws BeanFactoryException In case the object could not be found. + */ + T 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); +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java new file mode 100644 index 00000000..9110db9b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanFactoryException.java @@ -0,0 +1,42 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.general; + +/** + * Exception thrown by the BeanFactory if an object could not be found. + * + * @author Erik Brakkee + */ +public class BeanFactoryException extends RuntimeException { + static final long serialVersionUID = -1215992188624874902L; + + /** + * Constructs the exception. + * @param aMsg Message. + */ + public BeanFactoryException(String aMsg) { + super(aMsg); + } + + /** + * Constructs the exception. + * @param aMsg Message. + * @param aThrowable Cause of the exception. + */ + public BeanFactoryException(String aMsg, Throwable aThrowable) { + super(aMsg, aThrowable); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanKernel.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanKernel.java new file mode 100644 index 00000000..d05eef3d --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/BeanKernel.java @@ -0,0 +1,119 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.general; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.InputResource; + +/** + * The standard means to obtain the bean factory. This works by reading a + * property {@value #BEAN_FACTORY_CLASS} from a property file named + * {@value #BEAN_KERNEL_PROP_FILE} from the class path. This property identifies + * the bean factory implementation to use. The configured bean factory must have + * a no-arg constructor. + */ +public final class BeanKernel { + + private static final Log LOG = LogFactory.getLog(BeanKernel.class); + + /** + * Bean factory kernel properties file. + */ + private static final String BEAN_KERNEL_PROP_FILE = "org.wamblee.beanfactory.properties"; + + /** + * Name of the property to define the name of the bean factory class to use. + * THis class must have a public default constructor. + */ + private static final String BEAN_FACTORY_CLASS = "org.wamblee.beanfactory.class"; + + /** + * Cached bean factory. + */ + private static BeanFactory BEAN_FACTORY; + + /** + * Disabled constructor. + * + */ + private BeanKernel() { + // Empty + } + + /** + * Overrides the default mechanism for looking up the bean factory by + * specifying it yourself. + * + * @param aOverride + * Override bean factory. + */ + public static void overrideBeanFactory(BeanFactory aOverride) { + BEAN_FACTORY = aOverride; + } + + /** + * Gets the bean factory. + * + * @return Bean factory. + */ + public static BeanFactory getBeanFactory() { + synchronized (BeanFactory.class) { + if (BEAN_FACTORY == null) { + BEAN_FACTORY = lookupBeanFactory(BEAN_KERNEL_PROP_FILE); + } + } + return BEAN_FACTORY; + } + + /** + * Lookup the bean factory based on the properties file. + * + * @return Bean factory. + */ + static BeanFactory lookupBeanFactory(String aPropertyFilename) { + InputResource resource = new ClassPathResource(aPropertyFilename); + InputStream is; + try { + is = resource.getInputStream(); + } catch (IOException e) { + throw new BeanFactoryException("Cannot open resource " + resource, + e); + } + try { + Properties props = new Properties(); + props.load(is); + String className = props.getProperty(BEAN_FACTORY_CLASS); + Class beanFactory = Class.forName(className); + return (BeanFactory) beanFactory.newInstance(); + } catch (Exception e) { + throw new BeanFactoryException("Cannot read from resource " + + resource, e); + } finally { + try { + is.close(); + } catch (IOException e) { + // last resort cannot do much now. + LOG.error("Error closing resource " + resource); + } + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java new file mode 100644 index 00000000..5275e159 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/ClassLoaderUtils.java @@ -0,0 +1,98 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.general; + +import java.io.IOException; +import java.io.File; +import java.net.URLClassLoader; +import java.net.URL; +import java.lang.reflect.Method; + +/** + * Utility for working with the class loader. Based on the ClassPathHacker + * example found on the internet. + */ +public class ClassLoaderUtils { + + // No logging in this class to keep the required class libraries + // limited to the standard java classes. This allows use of the + // utilities in an environment with a very limited classpath. + + private static final String JAR_SUFFIX = ".jar"; + + /** + * Adds all jars in the given directory to the class path. + * @param aDirectory Directory. + * @throws IOException + */ + public static void addJarsInDirectory(File aDirectory) throws IOException { + System.out.println("directory '" + aDirectory + "'"); + + for (File aFile : aDirectory.listFiles()) { + System.out + .println("Considering '" + aFile.getCanonicalPath() + "'"); + if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) { + System.out.println("Adding '" + aFile.getCanonicalPath() + + "' to classpath."); + addFile(aFile); + } + } + } + + /** + * Adds a file to the classpath. + * @param aFilename Filename to add. + * @throws IOException + */ + public static void addFile(String aFilename) throws IOException { + File f = new File(aFilename); + addFile(f); + } + + /** + * Adds a file to the classpath. + * @param aFile File to add. + * @throws IOException + */ + public static void addFile(File aFile) throws IOException { + addURL(aFile.toURL()); + } + + /** + * Adds a url to the classpath. + * @param aUrl Url to add. + * @throws IOException + */ + public static void addURL(URL aUrl) throws IOException { + + URLClassLoader sysloader = (URLClassLoader) ClassLoader + .getSystemClassLoader(); + Class sysclass = URLClassLoader.class; + + try { + Method method = sysclass.getDeclaredMethod("addURL", new Class[]{ URL.class } ); + method.setAccessible(true); + method.invoke(sysloader, new Object[] { aUrl }); + } catch (Throwable t) { + t.printStackTrace(); + throw new IOException( + "Error, could not add URL to system classloader"); + } + + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/Pair.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/Pair.java new file mode 100644 index 00000000..2d90387f --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/Pair.java @@ -0,0 +1,80 @@ + + + +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.general; + +/** + * Represents a pair of objects. This is inspired on the C++ Standard Template + * Library pair template. + * + * @param + * Type of the first object. + * @param + * Type of the second object. + * + * @author Erik Brakkee + */ +public class Pair { + + private T _t; + + private U _u; + + /** + * Constructs the pair. + * + * @param aT + * First object. + * @param aU + * Second object. + */ + public Pair(T aT, U aU) { + _t = aT; + _u = aU; + } + + /** + * Copies a pair. + * + * @param aPair + * Pair to copy. + */ + public Pair(Pair aPair) { + _t = aPair._t; + _u = aPair._u; + } + + /** + * Gets the first object of the pair. + * + * @return First object. + */ + public T getFirst() { + return _t; + } + + /** + * Gets the second object of the pair. + * + * @return Second object. + */ + public U getSecond() { + return _u; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/package.html new file mode 100644 index 00000000..042270f2 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/general/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides several general purpose support classes. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/ClassPathResource.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/ClassPathResource.java new file mode 100644 index 00000000..32014a10 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/ClassPathResource.java @@ -0,0 +1,63 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Represents an input resource in the classpath. + */ +public class ClassPathResource implements InputResource { + /** + * Resource name. + */ + private String _resource; + + /** + * Construct the class path resource. + * + * @param aResource + * Resource + */ + public ClassPathResource(String aResource) { + _resource = aResource; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.io.InputResource#getInputStream() + */ + public InputStream getInputStream() throws IOException { + InputStream stream = Thread.currentThread().getContextClassLoader() + .getResourceAsStream(_resource); + if (stream == null) { + throw new IOException("Class path resource '" + _resource + + "' not found."); + } + return stream; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + return "ClassPathResource(" + _resource + ")"; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java new file mode 100644 index 00000000..029f33ef --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/DirectoryMonitor.java @@ -0,0 +1,108 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.io; + +import java.io.File; +import java.io.FileFilter; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Monitors a directory for changes. + * + * @author Erik Brakkee + */ +public class DirectoryMonitor { + + private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class); + + public static interface Listener { + + void fileChanged(File aFile); + + void fileCreated(File aFile); + + void fileDeleted(File aFile); + }; + + private File _directory; + private FileFilter _filter; + private Listener _listener; + private Map _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; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/FileResource.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/FileResource.java new file mode 100644 index 00000000..4f8c0ad9 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/FileResource.java @@ -0,0 +1,53 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Resource implemention for reading from a file. + * + * @author Erik Brakkee + */ +public class FileResource implements InputResource { + /** + * File to read. + */ + private File _file; + + /** + * Constructs the resource. + * + * @param aFile + * File to read. + */ + public FileResource(File aFile) { + _file = aFile; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.io.InputResource#getInputStream() + */ + public InputStream getInputStream() throws IOException { + return new BufferedInputStream(new FileInputStream(_file)); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/InputResource.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/InputResource.java new file mode 100644 index 00000000..2a0e8cda --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/InputResource.java @@ -0,0 +1,36 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Represents a resource from which information can be read. + * + * @author Erik Brakkee + */ +public interface InputResource { + /** + * Gets the input stream to the resource. The obtained input stream must be + * closed once reading has finished. + * + * @return Input stream to the resource, never null. + * @throws IOException + * in case the resource cannot be found. + */ + InputStream getInputStream() throws IOException; +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/SimpleProcess.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/SimpleProcess.java new file mode 100644 index 00000000..d4f7b16b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/SimpleProcess.java @@ -0,0 +1,168 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.StringWriter; +import java.io.Writer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class SimpleProcess { + + private static final Log LOG = LogFactory.getLog(SimpleProcess.class); + + private File _directory; + + private String[] _cmd; + + private String _stdout; + private String _stderr; + + public SimpleProcess(File aDirectory, String[] aCmd) { + _directory = aDirectory; + _cmd = aCmd; + } + + /** + * @return the stdout + */ + public String getStdout() { + return _stdout; + } + + /** + * @return the stderr + */ + public String getStderr() { + return _stderr; + } + + /** + * Runs the process and blocks until it is done. + * + * @return Exit status of the process. + * @throws IOException + * In case of problems. + */ + public int run() throws IOException { + return runImpl(); + } + + private int runImpl() throws IOException { + try { + String fullcmd = ""; + for (String part: _cmd) { + fullcmd += " " + part; + } + LOG.debug("Executing '" + fullcmd + "' in directory '" + _directory + + "'"); + java.lang.Process proc = Runtime.getRuntime().exec(_cmd, null, _directory); + + // Read standard output and error in separate threads to avoid + // deadlock. + + StringWriter stdout = new StringWriter(); + StringWriter stderr = new StringWriter(); + Thread stdoutReader = readAndLogStream("STDOUT> ", proc + .getInputStream(), stdout); + Thread stderrReader = readAndLogStream("STDERR> ", proc + .getErrorStream(), stderr); + + try { + proc.waitFor(); + } catch (InterruptedException e) { + IOException exception = new IOException( + "Process was terminated: " + this); + exception.initCause(e); + throw exception; + } + waitForReader(stdoutReader); + waitForReader(stderrReader); + + _stdout = stdout.toString(); + _stderr = stderr.toString(); + + if (proc.exitValue() != 0) { + LOG.warn("Exit value was non-zero: " + this); + } else { + LOG.debug("Process finished"); + } + return proc.exitValue(); + } catch (IOException e) { + IOException exception = new IOException("Error executing process: " + + this); + exception.initCause(e); + throw exception; + } + } + + private void waitForReader(Thread aReaderThread) { + try { + aReaderThread.join(); + } catch (InterruptedException e) { + LOG + .warn(this + + ": error waiting for output stream reader of process to finish"); + } + } + + private Thread readAndLogStream(final String aPrefix, + final InputStream aStream, final Writer aOutput) { + Thread inputReader = new Thread() { + @Override + public void run() { + BufferedReader br = null; + try { + br = new BufferedReader(new InputStreamReader(aStream)); + String str; + while ((str = br.readLine()) != null) { + LOG.debug(aPrefix + str); + aOutput.write(str); + } + } catch (IOException e) { + LOG.warn(SimpleProcess.this + ": error reading input stream", e); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + LOG.warn("Error closing stream " + aPrefix); + } + } + } + } + }; + inputReader.start(); + return inputReader; + } + + @Override + public String toString() { + String fullcmd = ""; + for (String part: _cmd) { + fullcmd += part + " "; + } + return "process(dir = '" + _directory + "', cmd = '" + fullcmd + "')"; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/StreamResource.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/StreamResource.java new file mode 100644 index 00000000..e3291aeb --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/StreamResource.java @@ -0,0 +1,50 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Input resource based on an input stream. + * + * @author Erik Brakkee + */ +public class StreamResource implements InputResource { + /** + * Input stream to read. + */ + private InputStream _stream; + + /** + * Constructs a resource. + * + * @param aStream + * Input stream to read. + */ + public StreamResource(InputStream aStream) { + _stream = aStream; + } + + /* + * (non-Javadoc) + * + * @see InputResource#getInputStream() + */ + public InputStream getInputStream() throws IOException { + return _stream; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/package.html new file mode 100644 index 00000000..2023c07b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/io/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides several support utilities for IO related functionality. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java new file mode 100644 index 00000000..0b14585c --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/DefaultObserverNotifier.java @@ -0,0 +1,47 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.observer; + +/** + * Default observer notifier which calls + * {@link org.wamblee.observer.Observer#send(ObservableType, Event)} + * immediately. + * + * @author Erik Brakkee + */ +public class DefaultObserverNotifier implements + ObserverNotifier { + + /** + * Constructs the notifier. + * + */ + public DefaultObserverNotifier() { + // Empty + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.observer.ObserverNotifier#update(org.wamblee.observer.Observer, + * ObservableType, Event) + */ + public void update(Observer aObserver, + ObservableType aObservable, Event aEvent) { + aObserver.send(aObservable, aEvent); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/Observable.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/Observable.java new file mode 100644 index 00000000..2980afaf --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/Observable.java @@ -0,0 +1,146 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.observer; + +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.log4j.Logger; + +/** + * Implements subscription and notification logic for an observer pattern. This + * class is thread safe. + */ +public class Observable { + + private static final Logger LOGGER = Logger.getLogger(Observable.class); + + /** + * Observable. + */ + private ObservableType _observable; + + /** + * Used to notify observers. + */ + private ObserverNotifier _notifier; + + /** + * Map of subscription to observer. + */ + private Map> _observers; + + /** + * Counter for subscriptions. Holds the next subscription. + */ + private long _counter; + + /** + * Constructs the observable. + * + * @param aObservable + * Observable this instance is used for. + * @param aNotifier + * Object used for implementing notification of listeners. + */ + public Observable(ObservableType aObservable, + ObserverNotifier aNotifier) { + _observable = aObservable; + _notifier = aNotifier; + _observers = new TreeMap>(); + _counter = 0; + } + + /** + * Subscribe an obvers. + * + * @param aObserver + * Observer to subscribe. + * @return Event Event to send. + */ + public synchronized long subscribe(Observer aObserver) { + long subscription = _counter++; // integer rage is so large it will + // never roll over. + _observers.put(subscription, aObserver); + return subscription; + } + + /** + * Unsubscribe an observer. + * + * @param aSubscription + * Subscription which is used + * @throws IllegalArgumentException + * In case the subscription is not known. + */ + public synchronized void unsubscribe(long aSubscription) { + Object obj = _observers.remove(aSubscription); + if (obj == null) { + throw new IllegalArgumentException("Subscription '" + aSubscription + + "'"); + } + } + + /** + * Gets the number of subscribed observers. + * + * @return Number of subscribed observers. + */ + public int getObserverCount() { + return _observers.size(); + } + + /** + * Notifies all subscribed observers. + * + * @param aEvent + * Event to send. + */ + public void send(Event aEvent) { + // Make sure we do the notification while not holding the lock to avoid + // potential deadlock + // situations. + List> observers = new ArrayList>(); + synchronized (this) { + observers.addAll(_observers.values()); + } + for (Observer observer : observers) { + _notifier.update(observer, _observable, aEvent); + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#finalize() + */ + @Override + protected void finalize() throws Throwable { + if (_observers.size() > 0) { + LOGGER + .error("Still observers registered at finalization of observer!"); + for (Observer observer : _observers.values()) { + LOGGER.error(" observer: " + observer); + } + } + + super.finalize(); + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/Observer.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/Observer.java new file mode 100644 index 00000000..a0e64314 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/Observer.java @@ -0,0 +1,32 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.observer; + +/** + * This is a type-safe version of {@link java.util.Observable}. + * + * @author Erik Brakkee + */ +public interface Observer { + + /** + * Called when an event has occurred on the observable. + * @param aObservable Observable. + * @param aEvent Event. + */ + void send(ObservableType aObservable, Event aEvent); +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java new file mode 100644 index 00000000..f09c5f0c --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/ObserverNotifier.java @@ -0,0 +1,35 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.observer; + +/** + * Implementation of notification of subscribers. + * + * @author Erik Brakkee + */ +public interface ObserverNotifier { + + /** + * Notifies an observer. + * + * @param aObserver Observer to notify + * @param aObservable Observable at which the event occured. + * @param aEvent Event that occured. + */ + void update(Observer aObserver, ObservableType aObservable, Event aEvent); + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/package.html new file mode 100644 index 00000000..35b6c3b0 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/observer/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides support for the observer pattern. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java new file mode 100644 index 00000000..4eee3a02 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/AbstractPersistent.java @@ -0,0 +1,83 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.persistence; + +import java.io.Serializable; + +/** + * Default implementation of Persistent. + * + * @author Erik Brakkee + */ +public abstract class AbstractPersistent implements Persistent { + + /** + * Primary key. + */ + private Serializable _primaryKey; + + /** + * Version. + */ + private int _version; + + /** + * Constructs the object. + * + */ + protected AbstractPersistent() { + _primaryKey = null; + _version = -1; + } + + /** + * Copy constructor. + * @param aPersistent Object to copy. + */ + protected AbstractPersistent(AbstractPersistent aPersistent) { + _primaryKey = aPersistent._primaryKey; + _version = aPersistent._version; + } + + /* (non-Javadoc) + * @see org.wamblee.persistence.Persistent#getPrimaryKey() + */ + public Serializable getPrimaryKey() { + return _primaryKey; + } + + /* (non-Javadoc) + * @see org.wamblee.persistence.Persistent#setPrimaryKey(java.io.Serializable) + */ + public void setPrimaryKey(Serializable aKey) { + _primaryKey = aKey; + } + + /* (non-Javadoc) + * @see org.wamblee.persistence.Persistent#getPersistedVersion() + */ + public int getPersistedVersion() { + return _version; + } + + /* (non-Javadoc) + * @see org.wamblee.persistence.Persistent#setPersistedVersion(int) + */ + public void setPersistedVersion(int aVersion) { + _version = aVersion; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/Persistent.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/Persistent.java new file mode 100644 index 00000000..57faf95e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/Persistent.java @@ -0,0 +1,58 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.persistence; + +import java.io.Serializable; + +/** + * Interface for persistent objects. This defines required functionality for all objects + * that are persisted. + * + * Objects that implement this interface and which implement + * {@link java.lang.Object#equals(java.lang.Object)} + * should exclude the primary key and version from determining equality. + */ +public interface Persistent { + + /** + * Gets the primary key. + * @return Primary key. + * @see #setPrimaryKey(Serializable) + */ + Serializable getPrimaryKey(); + + /** + * Sets the primary key. + * @param aKey Primary key. + * @see #getPrimaryKey() + */ + void setPrimaryKey(Serializable aKey); + + /** + * Gets the version. + * @return Version. + * @see #setPersistedVersion(int) + */ + int getPersistedVersion(); + + /** + * Sets the version. + * @param aVersion Version. + * @see #getPersistedVersion() + */ + void setPersistedVersion(int aVersion); +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/package.html new file mode 100644 index 00000000..cdca295e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/persistence/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides support for persistence. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java new file mode 100644 index 00000000..a1fa5522 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/reflection/ReflectionUtils.java @@ -0,0 +1,79 @@ +package org.wamblee.reflection; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ReflectionUtils { + + /** + * Wraps a type by the corresponding wrapper type if it is a primitive + * type. + * @param aClass Type to wrap. + * @return Wrapped type for primitives or the provided argument value. + */ + public static Class wrapIfNeeded(Class aClass) { + + if (aClass == boolean.class) { + return Boolean.class; + } + if (aClass == byte.class) { + return Byte.class; + } + if (aClass == char.class) { + return Character.class; + } + if (aClass == short.class) { + return Short.class; + } + if (aClass == int.class) { + return Integer.class; + } + if (aClass == long.class) { + return Long.class; + } + if (aClass == float.class) { + return Float.class; + } + if (aClass == double.class) { + return Double.class; + } + if (aClass == void.class) { + return Void.class; + } + return aClass; + } + + + public static List 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); + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java new file mode 100644 index 00000000..ba2d875c --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/ClasspathUriResolver.java @@ -0,0 +1,60 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.xml; + +import java.io.IOException; + +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.URIResolver; +import javax.xml.transform.stream.StreamSource; + +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.InputResource; + +/** + * URI resolver that resolves stylesheets through the classpath. + */ +public class ClasspathUriResolver implements URIResolver { + + /** + * Constructs the resolver. + * + */ + public ClasspathUriResolver() { + // Empty. + } + + /* + * (non-Javadoc) + * + * @see javax.xml.transform.URIResolver#resolve(java.lang.String, + * java.lang.String) + */ + public Source resolve(String aHref, String aBase) + throws TransformerException { + InputResource xslt = new ClassPathResource(aHref); + try { + return new StreamSource(xslt.getInputStream()); + } catch (IOException e) { + throw new TransformerException( + "Could not get XSLT style sheet in classpath '" + aHref + + "'", e); + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/DomUtils.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/DomUtils.java new file mode 100644 index 00000000..3825bacd --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/DomUtils.java @@ -0,0 +1,250 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.dom4j.DocumentException; +import org.dom4j.io.DOMReader; +import org.dom4j.io.DOMWriter; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +/** + * Some basic XML utilities for common reoccuring tasks for DOM documents. + * + * @author Erik Brakkee + */ +public final class DomUtils { + + private static final Log LOG = LogFactory.getLog(DomUtils.class); + + /** + * Disabled default constructor. + * + */ + private DomUtils() { + // Empty. + } + + /** + * Parses an XML document from a string. + * + * @param aDocument + * document. + * @return + */ + public static Document read(String aDocument) throws XMLException { + ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes()); + return read(is); + } + + /** + * Parses an XML document from a stream. + * + * @param aIs + * Input stream. + * @return + */ + public static Document read(InputStream aIs) throws XMLException { + try { + DocumentBuilder builder = DocumentBuilderFactory.newInstance() + .newDocumentBuilder(); + return builder.parse(aIs); + } catch (SAXException e) { + throw new XMLException(e.getMessage(), e); + } catch (IOException e) { + throw new XMLException(e.getMessage(), e); + } catch (ParserConfigurationException e) { + throw new XMLException(e.getMessage(), e); + } finally { + try { + aIs.close(); + } catch (Exception e) { + LOG.warn("Error closing XML file", e); + } + } + } + + /** + * Reads and validates a document against a schema. + * + * @param aIs + * Input stream. + * @param aSchema + * Schema. + * @return Parsed and validated document. + */ + public static Document readAndValidate(InputStream aIs, InputStream aSchema) + throws XMLException { + + try { + final Schema schema = SchemaFactory.newInstance( + XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema( + new StreamSource(aSchema)); + + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setValidating(true); + factory.setNamespaceAware(true); + factory.setSchema(schema); + + return factory.newDocumentBuilder().parse(aIs); + } catch (SAXException e) { + throw new XMLException(e.getMessage(), e); + } catch (IOException e) { + throw new XMLException(e.getMessage(), e); + } catch (ParserConfigurationException e) { + throw new XMLException(e.getMessage(), e); + } finally { + try { + aSchema.close(); + } catch (Exception e) { + LOG.warn("Error closing schema", e); + } + try { + aIs.close(); + } catch (Exception e) { + LOG.warn("Error closing XML file", e); + } + } + + } + + /** + * Serializes an XML document to a stream. + * + * @param aDocument + * Document to serialize. + * @param aOs + * Output stream. + */ + public static void serialize(Document aDocument, OutputStream aOs) + throws IOException { + XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat()); + serializer.serialize(aDocument); + } + + /** + * Serializes an XML document. + * + * @param aDocument + * Document to serialize. + * @return Serialized document. + */ + public static String serialize(Document aDocument) throws IOException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + serialize(aDocument, os); + return os.toString(); + } + + /** + * Converts a dom4j document into a w3c DOM document. + * + * @param aDocument + * Document to convert. + * @return W3C DOM document. + */ + public static Document convert(org.dom4j.Document aDocument) + throws DocumentException { + return new DOMWriter().write(aDocument); + } + + /** + * Converts a W3C DOM document into a dom4j document. + * + * @param aDocument + * Document to convert. + * @return Dom4j document. + */ + public static org.dom4j.Document convert(Document aDocument) { + return new DOMReader().read(aDocument); + } + + /** + * Removes duplicate attributes from a DOM tree.This is useful for + * postprocessing the output of JTidy as a workaround for a bug in JTidy. + * + * @param aNode + * Node to remove duplicate attributes from (recursively). + * Attributes of the node itself are not dealt with. Only the + * child nodes are dealt with. + */ + public static void removeDuplicateAttributes(Node aNode) { + NodeList list = aNode.getChildNodes(); + for (int i = 0; i < list.getLength(); i++) { + Node node = list.item(i); + if (node instanceof Element) { + removeDuplicateAttributes((Element) node); + removeDuplicateAttributes(node); + } + } + } + + /** + * Removes duplicate attributes from an element. + * + * @param aElement + * Element. + */ + private static void removeDuplicateAttributes(Element aElement) { + NamedNodeMap attributes = aElement.getAttributes(); + Map uniqueAttributes = new TreeMap(); + 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() + "'"); + } + uniqueAttributes.put(attribute.getNodeName(), attribute); + attlist.add(attribute); + } + // Remove all attributes from the element. + for (Attr att : attlist) { + aElement.removeAttributeNode(att); + } + // Add the unique attributes back to the element. + for (Attr att : uniqueAttributes.values()) { + aElement.setAttributeNode(att); + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/XMLException.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/XMLException.java new file mode 100644 index 00000000..06363c42 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/XMLException.java @@ -0,0 +1,33 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.xml; + +/** + * Exception thrown in case of XML parsing problems. + * + * @author Erik Brakkee + */ +public class XMLException extends Exception { + + public XMLException(String aMsg) { + super(aMsg); + } + + public XMLException(String aMsg, Throwable aCause) { + super(aMsg, aCause); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/XslTransformer.java b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/XslTransformer.java new file mode 100644 index 00000000..fb3d3052 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/XslTransformer.java @@ -0,0 +1,176 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package org.wamblee.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.URIResolver; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import org.w3c.dom.Document; +import org.wamblee.io.FileResource; + +/** + * XSL transformer for simplified usage of XSL transformations. + * + * @author Erik Brakkee + */ +public class XslTransformer { + + private TransformerFactory _factory; + + /** + * Constructs the URL resolver. + * + * @param aResolver + * URI resolver to use. + */ + public XslTransformer(URIResolver aResolver) { + _factory = TransformerFactory.newInstance(); + _factory.setURIResolver(aResolver); + } + + /** + * Constructs the XSLT processor. + * + */ + public XslTransformer() { + _factory = TransformerFactory.newInstance(); + } + + /** + * Resolves an XSLT based on URI. + * @param aXslt XSLT to resolve, + * @return Source for the XSLT + * @throws TransformerException In case the XSLT cannot be found. + */ + public Source resolve(String aXslt) throws TransformerException { + URIResolver resolver = _factory.getURIResolver(); + if (resolver == null) { + if (new File(aXslt).canRead()) { + try { + return new StreamSource(new FileResource(new File(aXslt)) + .getInputStream()); + } catch (IOException e) { + throw new TransformerException(e.getMessage(), e); + } + } else { + throw new TransformerException("Cannot read '" + aXslt + "'"); + } + } + return resolver.resolve(aXslt, ""); + } + + /** + * Transforms a DOM document into another DOM document using a given XSLT + * transformation. + * + * @param aDocument + * Document to transform. + * @param aXslt + * XSLT to use. + * @return Transformed document. + * @throws IOException + * In case of problems reading resources. + * @throws TransformerException + * In case transformation fails. + */ + public Document transform(Document aDocument, Source aXslt) + throws IOException, TransformerException { + Source source = new DOMSource(aDocument); + DOMResult result = new DOMResult(); + transform(source, result, aXslt); + return (Document) result.getNode(); + } + + /** + * Transforms a document using XSLT. + * + * @param aDocument + * Document to transform. + * @param aXslt + * XSLT to use. + * @return Transformed document. + * @throws IOException + * In case of problems reading resources. + * @throws TransformerException + * In case transformation fails. + */ + public Document transform(byte[] aDocument, Source aXslt) + throws IOException, TransformerException { + Source source = new StreamSource(new ByteArrayInputStream(aDocument)); + DOMResult result = new DOMResult(); + transform(source, result, aXslt); + return (Document) result.getNode(); + } + + /** + * Transforms a document to a text output. This supports XSLT + * transformations that result in text documents. + * + * @param aDocument + * Document to transform. + * @param aXslt + * XSL transformation. + * @return Transformed document. + */ + public String textTransform(byte[] aDocument, Source aXslt) + throws IOException, TransformerException { + Source source = new StreamSource(new ByteArrayInputStream(aDocument)); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + StreamResult result = new StreamResult(os); + transform(source, result, aXslt); + return new String(os.toByteArray()); + } + + /** + * Transforms a document using XSLT. + * + * @param aSource + * Document to transform. + * @param aResult + * Result of the transformation. + * @param aXslt + * XSLT to use. + * @throws IOException + * In case of problems reading resources. + * @throws TransformerException + * In case transformation fails. + */ + public void transform(Source aSource, Result aResult, Source aXslt) + throws IOException, TransformerException { + try { + Transformer transformer = _factory.newTransformer(aXslt); + transformer.transform(aSource, aResult); + } catch (TransformerConfigurationException e) { + throw new TransformerException( + "Configuration problem of XSLT transformation", e); + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/package.html b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/package.html new file mode 100644 index 00000000..5d1c9e81 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/java/org/wamblee/xml/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides support utilities for XML processing. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/main/resources/log4j.properties b/tags/wamblee-utils-0.2/support/general/src/main/resources/log4j.properties new file mode 100644 index 00000000..b953f9b3 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/main/resources/log4j.properties @@ -0,0 +1,56 @@ + +############################################################################################ +# Default configuration file for log4j. +# +# This properties file is used if no other configuration if log4j is done explicitly. +############################################################################################ + + +# Root logger reports everything and uses the console appender +log4j.rootLogger=ERROR, console + +# Log level for wamblee.org +log4j.logger.org.wamblee=INFO +log4j.logger.org.wamblee.usermgt.UserAdministrationImplTest=INFO +log4j.logger.org.wamblee.security.authorization=ERROR +log4j.logger.org.wamblee.cache=INFO +log4j.logger.org.wamblee.crawler=DEBUG + +log4j.logger.org.springframework=ERROR +log4j.logger.net.sf.ehcache=WARN + +# Default log level for hibernate +log4j.logger.org.hibernate=ERROR +log4j.logger.org.hibernate3=ERROR + +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n + +###################################################################################### +# Hibernate SQL logging, switch the log level to DEBUG to see the output. +###################################################################################### + +log4j.logger.org.wamblee.test.SpringTestCase=ERROR, console +log4j.additivity.org.wamblee.test.SpringTestCase=false + +# Logging for queries. +log4j.logger.org.hibernate.SQL=ERROR, sql +log4j.additivity.org.hibernate.SQL=false + +# Logging for query parameters and return values. +log4j.logger.org.hibernate.type=ERROR, sqltype +log4j.additivity.org.hibernate.type=false + +# Appender for the queries +log4j.appender.sql=org.apache.log4j.ConsoleAppender +log4j.appender.sql.layout=org.apache.log4j.PatternLayout +log4j.appender.sql.layout.ConversionPattern=%n%-4r [%t] SQL: %x - %m%n + +# Appender to show the actual parameters and return values of the queries. +log4j.appender.sqltype=org.apache.log4j.ConsoleAppender +log4j.appender.sqltype.layout=org.apache.log4j.PatternLayout +log4j.appender.sqltype.layout.ConversionPattern=%-4r [%t] SQL: %x - %m%n + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java new file mode 100644 index 00000000..da6e1be6 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/cache/CachedObjectTest.java @@ -0,0 +1,176 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.cache; + +import java.io.IOException; + +import junit.framework.TestCase; +import net.sf.ehcache.CacheException; + +import org.wamblee.io.TestResource; +import org.wamblee.test.TimingUtils; + +/** + * Cached object test. + * + * @author Erik Brakkee + */ +public class CachedObjectTest extends TestCase { + + /** + * + */ + private static final String EHCACHE_CONFIG = "ehcache.xml"; + + private static final int OBJECT_KEY = 10; + + private CachedObject.Computation _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; + } + + private int compute(int aValue) { + return aValue + 10; + } + + 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. + * + */ + public void testComputation() { + CachedObject cached = createCached(new ZeroCache()); + int value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + } + + public void testInvalidateCache() { + CachedObject cached = createCached(new ForeverCache()); + int value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + cached.invalidate(); + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(2, _ncomputations); + } + + public void testBehaviorEhCache() throws CacheException, IOException { + Cache cache = new EhCache(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "test"); + CachedObject cached = createCached(cache); + + assertTrue( cache == cached.getCache()); + int value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + // The value must still be cached. + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + + // Cache expiry. + TimingUtils.sleep(6000); + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(2, _ncomputations); + + // Should still be cached now. + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(2, _ncomputations); + + // explicit invalidation. + cached.invalidate(); + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(3, _ncomputations); + + } + + public void testBehaviorEhCacheDefault() throws CacheException, IOException { + Cache cache = new EhCache(new TestResource(CachedObjectTest.class, EHCACHE_CONFIG), "undefined"); + CachedObject cached = createCached(cache); + + assertTrue( cache == cached.getCache()); + int value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + // The value must still be cached. + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + + // Cache expiry. + TimingUtils.sleep(6000); + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(2, _ncomputations); + + // Should still be cached now. + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(2, _ncomputations); + + } + + + public void testBehaviorForeverCache() { + CachedObject 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(compute(OBJECT_KEY), value); + assertEquals(1, _ncomputations); + } + } + + 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(compute(OBJECT_KEY), value); + assertEquals(ncomp, _ncomputations); + } + cached.invalidate(); + value = cached.get(); + assertEquals(compute(OBJECT_KEY), value); + assertEquals(101, _ncomputations); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java new file mode 100644 index 00000000..1e56eac1 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/collections/CollectionFilterTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.collections; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.wamblee.conditions.Condition; +import org.wamblee.test.AssertionUtils; + +import junit.framework.TestCase; + +public class CollectionFilterTest extends TestCase { + + public void testFilter() { + List 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/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java new file mode 100644 index 00000000..39cec11a --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/AbstractLockTestCase.java @@ -0,0 +1,92 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.concurrency; + +import org.wamblee.test.EventTracker; +import org.wamblee.test.TimingUtils; + +import junit.framework.TestCase; + +/** + * Tests for the JVMLock. + * + * @author Erik Brakkee + */ +public abstract class AbstractLockTestCase extends TestCase { + + protected static final int SLEEP_TIME = 1000; + + protected static final String STARTED = "started"; + + protected static final String ACQUIRED = "acquired"; + + protected static final String RELEASED = "released"; + + private EventTracker _tracker; + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + _tracker = new EventTracker(); + } + + protected EventTracker getTracker() { + return _tracker; + } + + /** + * Must be implemented to generate the events + * {@link #STARTED}, {@link #ACQUIRED}, and {@link #RELEASED} in + * that order. The lock should be acquired for + * the time specified by {@link #SLEEP_TIME}. + * @return Thread which does the work. + */ + protected abstract Thread runThread(); + + /** + * Tests the operation of the lock. + */ + public void testLock() throws InterruptedException { + Thread t1 = runThread(); + Thread t2 = runThread(); + TimingUtils.sleep(SLEEP_TIME / 10); // give threads a chance to start + // up. + assertEquals(2, _tracker.getEventCount(STARTED)); // both threads + // should have + // started. + assertEquals(1, _tracker.getEventCount(ACQUIRED)); // one thread has + // acquired the + // lock. + TimingUtils.sleep(SLEEP_TIME); + assertEquals(2, _tracker.getEventCount(ACQUIRED)); // now the other + // thread could also + // acquire the lock + assertEquals(1, _tracker.getEventCount(RELEASED)); // and the first + // thread has + // released it. + TimingUtils.sleep(SLEEP_TIME); + assertEquals(2, _tracker.getEventCount(RELEASED)); // both threads + // should be + // finished. + t1.join(); + t2.join(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java new file mode 100644 index 00000000..e14ca9ba --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/JvmLockTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.concurrency; + +import org.wamblee.test.TimingUtils; + +/** + * Tests for the JVMLock. + * + * @author Erik Brakkee + */ +public class JvmLockTest extends AbstractLockTestCase { + + private JvmLock _lock; + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + _lock = new JvmLock(); + } + + protected Thread runThread() { + Thread t = new Thread(new Runnable() { + public void run() { + getTracker().eventOccurred(STARTED); + _lock.acquire(); + getTracker().eventOccurred(ACQUIRED); + TimingUtils.sleep(SLEEP_TIME); + _lock.release(); + getTracker().eventOccurred(RELEASED); + }; + }); + t.start(); + return t; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java new file mode 100644 index 00000000..40302f76 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/concurrency/ReadWriteLockTest.java @@ -0,0 +1,509 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.concurrency; + +import junit.framework.Assert; +import junit.framework.TestCase; + + +/** + * Testing the read-write lock class. Note: in case of problems, test cases + * could hang. + * + * @see ReadWriteLock + */ +public class ReadWriteLockTest extends TestCase { + /** + * + */ + private static final int HALF_SECOND = 500; + /** + * + */ + private static final int ONE_SECOND = 1000; + /** + * + */ + private static final int TWO_SECONDS = 2000; + private ReadWriteLock _lock; + private int _nReaders; + private int _nWriters; + + /** + * Constructor for ReadWriteLockTest. + * + * @param aName + */ + public ReadWriteLockTest(String aName) { + super(aName); + } + + private synchronized int getReaderCount() { + return _nReaders; + } + + private synchronized int getWriterCount() { + return _nWriters; + } + + synchronized void incrementReaderCount() { + _nReaders++; + } + + synchronized void incrementWriterCount() { + _nWriters++; + } + + synchronized void decrementReaderCount() { + _nReaders--; + } + + synchronized void decrementWriterCount() { + _nWriters--; + } + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + _lock = new ReadWriteLock(); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + _lock = null; + super.tearDown(); + } + + /** + * Acquire and release a read lock. + */ + public void testRead() { + _lock.acquireRead(); + _lock.releaseRead(); + } + + /** + * Acquire and release a write lock. + */ + public void testWrite() { + _lock.acquireWrite(); + _lock.releaseWrite(); + } + + /** + * Verify concurrent access by multiple readers is possible. + * + * @throws InterruptedException May not occur. + */ + public void testMultipleReaders() throws InterruptedException { + Runnable runnable = new ReadLocker(_lock, this, TWO_SECONDS); + + Thread t1 = new Thread(runnable); + t1.start(); + + Thread t2 = new Thread(runnable); + t2.start(); + Thread.sleep(ONE_SECOND); + assertTrue("Not enough readers!", getReaderCount() == 2); + t1.join(); + t2.join(); + } + + /** + * Verify that only one writer at a time can acquire the write lock. + * + * @throws InterruptedException May not occur. + */ + public void testSingleWriter() throws InterruptedException { + WriteLocker writer = new WriteLocker(_lock, this, ONE_SECOND); + Thread t1 = new Thread(writer); + Thread t2 = new Thread(writer); + + t1.start(); + t2.start(); + Thread.sleep(HALF_SECOND); + assertTrue("Wrong writer count: " + getWriterCount(), + getWriterCount() == 1); + t1.join(); + t2.join(); + } + + /** + * Verify that multiple writers cannot acquire the write lock concurrently. + * + * @throws InterruptedException May not occur. + */ + public void testMultipleWriters() throws InterruptedException { + WriteLocker writer1 = new WriteLocker(_lock, this, HALF_SECOND + ONE_SECOND); + WriteLocker writer2 = new WriteLocker(_lock, this, ONE_SECOND); + Thread t1 = new Thread(writer1); + Thread t2 = new Thread(writer2); + + t1.start(); + Thread.sleep(HALF_SECOND); + assertTrue(getWriterCount() == 1); + t2.start(); + Thread.sleep(HALF_SECOND); + assertTrue(getWriterCount() == 1); // first writer still + + // has the lock. + Thread.sleep(ONE_SECOND); + + // at t = 2, the second writer still must have + // a lock. + assertTrue(getWriterCount() == 1); + t1.join(); + t2.join(); + } + + /** + * Verify that after the first reader acquires a lock, a subsequent writer + * can only acquire the lock after the reader has released it. + * + * @throws InterruptedException May not occur. + */ + public void testReadWrite1() throws InterruptedException { + ReadLocker readLocker = new ReadLocker(_lock, this, TWO_SECONDS); + Thread t1 = new Thread(readLocker); + WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS); + Thread t2 = new Thread(writeLocker); + + t1.start(); // acquire read lock + Thread.sleep(HALF_SECOND); + assertTrue(getReaderCount() == 1); + t2.start(); + Thread.sleep(HALF_SECOND); + + // 1 second underway, reader still holding the + // lock so write lock cannot be acquired. + assertTrue(getReaderCount() == 1); + assertTrue(getWriterCount() == 0); + Thread.sleep(ONE_SECOND + HALF_SECOND); + + // 2.5 seconds underway, read lock released and + // write lock must be acquired. + assertTrue("Wrong no. of readers: " + getReaderCount(), + getReaderCount() == 0); + assertTrue(getWriterCount() == 1); + t1.join(); + t2.join(); + } + + /** + * Verify that when multiple readers have acquired a read lock, the writer + * can only acquire the lock after all readers have released it. + * + * @throws InterruptedException May not occur. + */ + public void testReadWrite2() throws InterruptedException { + ReadLocker readLocker1 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND); + ReadLocker readLocker2 = new ReadLocker(_lock, this, TWO_SECONDS + HALF_SECOND); + Thread t1 = new Thread(readLocker1); + Thread t2 = new Thread(readLocker2); + WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS); + Thread t3 = new Thread(writeLocker); + + t1.start(); // acquire read lock [0, 2.5] + Thread.sleep(ONE_SECOND); + // t = 1 + assertTrue(getReaderCount() == 1); + t2.start(); // acquire read lock [1, 3.5] + Thread.sleep(HALF_SECOND); + // t = 1.5 + assertTrue(getReaderCount() == 2); + t3.start(); // write lock + Thread.sleep(HALF_SECOND); + + // 2 seconds, + assertTrue(getReaderCount() == 2); + assertTrue(getWriterCount() == 0); + Thread.sleep(ONE_SECOND); + + // 3 seconds underway, first read lock must + // have been released. + assertTrue(getReaderCount() == 1); + assertTrue(getWriterCount() == 0); + Thread.sleep(ONE_SECOND); + + // 4 seconds underway, write lock must have + // been acquired. + assertTrue(getReaderCount() == 0); + assertTrue(getWriterCount() == 1); + + t1.join(); + t2.join(); + t3.join(); + } + + /** + * Verify that after a writer acquires a lock, a subsequent reader can + * only acquire the lock after the writer has released it. + * + * @throws InterruptedException May not occur. + */ + public void testReadWrite3() throws InterruptedException { + ReadLocker readLocker = new ReadLocker(_lock, this, TWO_SECONDS); + Thread t1 = new Thread(readLocker); + WriteLocker writeLocker = new WriteLocker(_lock, this, TWO_SECONDS); + Thread t2 = new Thread(writeLocker); + + t2.start(); // acquire write lock + Thread.sleep(HALF_SECOND); + assertTrue(getWriterCount() == 1); + t1.start(); + Thread.sleep(HALF_SECOND); + + // 1 second underway, writer still holding the + // lock so read lock cannot be acquired. + assertTrue(getWriterCount() == 1); + assertTrue(getReaderCount() == 0); + Thread.sleep(ONE_SECOND + HALF_SECOND); + + // 2.5 seconds underway, write lock released and + // read lock must be acquired. + assertTrue("Wrong no. of writers: " + getReaderCount(), + getWriterCount() == 0); + assertTrue(getReaderCount() == 1); + t1.join(); + t2.join(); + } + + /* + * The following test cases are for testing whether or not + * the read write lock checks the locking correctly. + * Strictly speaking, these checks wouldn't be necessary + * because it involves the contract of the ReadWriteLock which + * must be obeyed by users of the ReadWriteLock. Nevertheless, + * this is tested anyway to be absolutely sure. + */ + + /** + * Acquire a read lock from one thread, release it from another. Verify + * that a RuntimeException is thrown. + * + * @throws InterruptedException May not occur. + */ + public void testReleaseReadFromWrongThread() throws InterruptedException { + Thread t1 = null; + + try { + t1 = new Thread(new Runnable() { + public void run() { + ReadWriteLockTest.this._lock.acquireRead(); + } + }); + t1.start(); + Thread.sleep(ONE_SECOND); // wait until thread is started + _lock.releaseRead(); // release lock from wrong thread. + } catch (RuntimeException e) { + return; // ok + } finally { + t1.join(); + } + + fail(); + } + + /** + * Acquire a write lock from one thread, release it from another. Verify + * that a RuntimeException is thrown. + * + * @throws InterruptedException May not occur. + */ + public void testReleaseWriteFromWrongThread() throws InterruptedException { + Thread t1 = null; + + try { + t1 = new Thread(new Runnable() { + public void run() { + ReadWriteLockTest.this._lock.acquireWrite(); + } + }); + t1.start(); + Thread.sleep(ONE_SECOND); // wait until thread is started + _lock.releaseWrite(); // release lock from wrong thread. + } catch (RuntimeException e) { + return; // ok + } finally { + t1.join(); + } + + fail(); + } + + /** + * Try to acquire a read lock multiple times. Verify that a + * RuntimeException is thrown. + */ + public void testAcquireReadTwice() { + try { + _lock.acquireRead(); + _lock.acquireRead(); + } catch (RuntimeException e) { + // ok + return; + } + + fail(); + } + + /** + * Try to acquire a write lock multiple times. Verify that a + * RuntimeException is thrown. + */ + public void testAcquireWriteTwice() { + try { + _lock.acquireWrite(); + _lock.acquireWrite(); + } catch (RuntimeException e) { + return; // ok + } + + fail(); + } + + /** + * Acquire the lock for reading and directly afterwards acquire it for + * writing. Verify that a RuntimeException is thrown. + */ + public void testAcquireReadFollowedByWrite() { + try { + _lock.acquireRead(); + _lock.acquireWrite(); + } catch (RuntimeException e) { + return; // ok + } + + fail(); + } + + /** + * Acquire the lock for writing and directly afterwards acquire it for + * reading. Verify that a RuntimeException is thrown. + */ + public void testAcquireWriteFollowedByRead() { + try { + _lock.acquireWrite(); + _lock.acquireRead(); + } catch (RuntimeException e) { + return; // ok + } + + fail(); + } + + /** + * Acquire a read lock and release it as a write lock. Verify that a + * RuntimeException is thrown. + */ + public void testAcquireReadFollowedByReleaseaWrite() { + try { + _lock.acquireRead(); + _lock.releaseWrite(); + } catch (RuntimeException e) { + return; // ok + } + + fail(); + } + + /** + * Acquire a write lock and release it as a read lock. Verify that a + * RuntimeException is thrown. + */ + public void testAcquireWriteFollowedByReleaseRead() { + try { + _lock.acquireWrite(); + _lock.releaseRead(); + } catch (RuntimeException e) { + return; // ok + } + + fail(); + } +} + + +/** + * ReadLocker acquires a read lock and performs a callback when the lock as + * been acquired, sleeps for a designated amount of time, releases the read + * lock, and performs a callback after the lock has been released. + */ +class ReadLocker implements Runnable { + private ReadWriteLock _lock; + private ReadWriteLockTest _lockTest; + private int _sleepTime; + + public ReadLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest, + int aSleepTime) { + _lock = aLock; + _lockTest = aLockTest; + _sleepTime = aSleepTime; + } + + public void run() { + _lock.acquireRead(); + _lockTest.incrementReaderCount(); + + try { + Thread.sleep(_sleepTime); + } catch (InterruptedException e) { + Assert.fail("ReadLocker thread was interrupted." + + Thread.currentThread()); + } + + _lock.releaseRead(); + _lockTest.decrementReaderCount(); + } +} + + +/** + * WriteLocker acquires a write lock and performs a callback when the lock as + * been acquired, sleeps for a designated amount of time, releases the write + * lock, and performs a callback after the lock has been released. + */ +class WriteLocker implements Runnable { + private ReadWriteLock _lock; + private ReadWriteLockTest _lockTest; + private int _sleepTime; + + public WriteLocker(ReadWriteLock aLock, ReadWriteLockTest aLockTest, + int aSleepTime) { + _lock = aLock; + _lockTest = aLockTest; + _sleepTime = aSleepTime; + } + + public void run() { + _lock.acquireWrite(); + _lockTest.incrementWriterCount(); + + try { + Thread.sleep(_sleepTime); + } catch (InterruptedException e) { + Assert.fail("WriteLocker thread was interrupted: " + + Thread.currentThread()); + } + + _lock.releaseWrite(); + _lockTest.decrementWriterCount(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java new file mode 100644 index 00000000..81c4e4ed --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/AndConditionTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +/** + * Tests the Or Condition. + * + * @author Erik Brakkee + */ +public class AndConditionTest extends TestCase { + + public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { + AndCondition and = new AndCondition(new FixedCondition(aFirst), + new FixedCondition(aSecond)); + assertEquals(aResult, and.matches(0)); + } + + public void checkResult(boolean[] aValues, boolean aResult) { + List> conditions = new ArrayList>(); + 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. + * + */ + public void testTwoConditions() { + checkResult(false, false, false); + checkResult(true, false, false); + checkResult(false, true, false); + checkResult(true, true, true); + } + + public void testMultipleConditions() { + checkResult(new boolean[]{ false, false, false} , false); + checkResult(new boolean[]{ true, false, false }, false); + checkResult(new boolean[]{ false, true, false }, false); + checkResult(new boolean[]{ false, false, true }, false); + checkResult(new boolean[]{ true, true, true }, true); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java new file mode 100644 index 00000000..bdb95897 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/GreaterThanCondition.java @@ -0,0 +1,39 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +/** + * Test condition object. + * + * @author Erik Brakkee + */ +public class GreaterThanCondition implements Condition { + + private int _value; + + public GreaterThanCondition(int aValue) { + _value = aValue; + } + + /* (non-Javadoc) + * @see org.wamblee.conditions.Condition#matches(T) + */ + public boolean matches(Integer aObject) { + return aObject > _value; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java new file mode 100644 index 00000000..06ab192a --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/LessThanCondition.java @@ -0,0 +1,39 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +/** + * Test condition object. + * + * @author Erik Brakkee + */ +public class LessThanCondition implements Condition { + + private int _value; + + public LessThanCondition(int aValue) { + _value = aValue; + } + + /* (non-Javadoc) + * @see org.wamblee.conditions.Condition#matches(T) + */ + public boolean matches(Integer aObject) { + return aObject < _value; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java new file mode 100644 index 00000000..c3f7df1e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/OrConditionTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +/** + * Tests the Or Condition. + * + * @author Erik Brakkee + */ +public class OrConditionTest extends TestCase { + + public void checkResult(boolean aFirst, boolean aSecond, boolean aResult) { + OrCondition or = new OrCondition(new FixedCondition(aFirst), + new FixedCondition(aSecond)); + assertEquals(aResult, or.matches(0)); + } + + public void checkResult(boolean[] aValues, boolean aResult) { + List> conditions = new ArrayList>(); + 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. + * + */ + public void testTwoConditions() { + checkResult(false, false, false); + checkResult(true, false, true); + checkResult(false, true, true); + checkResult(true, true, true); + } + + public void testMultipleConditions() { + checkResult(new boolean[]{ false, false, false} , false); + checkResult(new boolean[]{ true, false, false }, true); + checkResult(new boolean[]{ false, true, false }, true); + checkResult(new boolean[]{ false, false, true }, true); + checkResult(new boolean[]{ true, true, true }, true); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java new file mode 100644 index 00000000..9f494fb6 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/PropertyRegexConditionTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +import junit.framework.TestCase; + +/** + * Tests {@link org.wamblee.conditions.PropertyRegexCondition}. + * + * @author Erik Brakkee + */ +public class PropertyRegexConditionTest extends TestCase { + + private boolean match(String aProperty, String aRegex, boolean aToLower, TestBean aBean) { + PropertyRegexCondition 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)); + } + + /** + * Verifies correct matching behavior for several cases. + * + */ + public void testMatchProperty() { + TestBean bean = new TestBean("Hallo"); + checkMatch("value", "Hallo", false, bean, true); + checkMatch("value", "all", false, bean, false); + checkMatch("value", ".a.*o", false, bean, true); + checkMatch("value", "hallo", false, bean, false); // no match when not converting to lower case. + checkMatch("value", "hallo", true, bean, true); // match! + } + + /** + * Uses property regex condition for non-existing property. + * Verifies that a runtime exception is thrown. + * + */ + public void testWrongProperty() { + TestBean bean = new TestBean("Hallo"); + try { + match("bla", ".*", false, bean); + } catch (RuntimeException e) { + return; // ok + } + fail(); + } + + /** + * Applies condition to a private property. Verifies that a runtime + * exception is thrown. + * + */ + public void testPrivateProperty() { + TestBean bean = new TestBean("Hallo"); + try { + match("privateValue", ".*", false, bean); + } catch (RuntimeException e) { + return; // ok + } + fail(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/TestBean.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/TestBean.java new file mode 100644 index 00000000..7bcd6d20 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/conditions/TestBean.java @@ -0,0 +1,39 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.conditions; + +/** + * + * + * @author Erik Brakkee + */ +public class TestBean { + + private String _value; + + public TestBean(String aValue) { + _value = aValue; + } + + public String getValue() { + return _value; + } + + private String getPrivateValue() { + return _value; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java new file mode 100644 index 00000000..2c9f898f --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/BeanKernelTest.java @@ -0,0 +1,88 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.general; + +import junit.framework.TestCase; + +/** + * Tests the bean kernel. The lookup of the bean factory itself can be tested + * only partially. Using a global property file for all test cases would tie all + * test cases together therefore no global property file is used. + * + * @author Erik Brakkee + */ +public class BeanKernelTest extends TestCase { + + /** + * Loads the bean factory based on a property file configuration. Verifies + * the correct bean factory is loaded. + * + */ + public void testLoadBeanFactoryFromProperties() { + BeanFactory factory = BeanKernel + .lookupBeanFactory("org/wamblee/general/beankernel.properties"); + assertTrue(factory instanceof TestBeanFactory); + } + + /** + * Loads the bean factory based on a non-existing property file. + * Verifies that BeanFactoryException is thrown. + * + */ + public void testNonExistentPropertyFile() { + try { + BeanKernel + .lookupBeanFactory("org/wamblee/general/beankernel-nonexistent.properties"); + } catch (BeanFactoryException e) { + return; // ok + } + fail(); + } + + /** + * Loads the bean factory based on a property file with a non-existing + * bean factory defined in it. + * Verifies that BeanFactoryException is thrown. + * + */ + public void testNonExistentBeanFactory() { + try { + BeanKernel + .lookupBeanFactory("org/wamblee/general/beankernel-wrong.properties"); + } catch (BeanFactoryException e) { + return; // ok + } + fail(); + } + + + /** + * Retrieves a bean factory throug the bean kernel. Verifies that beans can + * be retrieved. + * + */ + public void testRetrieveFactory() { + BeanKernel.overrideBeanFactory(new TestBeanFactory()); // bypass + // default + // property + // lookup + BeanFactory factory = BeanKernel.getBeanFactory(); + assertNotNull(factory); + assertEquals("hello", factory.find(String.class)); + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/PairTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/PairTest.java new file mode 100644 index 00000000..dcb6f614 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/PairTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.general; + +import junit.framework.TestCase; + +/** + * Tests the pair class. + */ +public class PairTest extends TestCase { + + public void testPair() { + Pair 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/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java new file mode 100644 index 00000000..6198e9ba --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/general/TestBeanFactory.java @@ -0,0 +1,38 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.general; + +public class TestBeanFactory implements BeanFactory { + + @Override + public Object find(String aId) { + return null; + } + + @Override + public T find(Class aClass) { + if ( aClass.equals(String.class)) { + return (T)"hello"; + } + return null; + } + + @Override + public T find(String aId, Class aClass) { + return null; + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java new file mode 100644 index 00000000..70b05ab5 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/ClassPathResourceTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.io; + +import java.io.IOException; +import java.io.InputStream; + + +import junit.framework.TestCase; + +/** + * Tests for the classpath resource. + */ +public class ClassPathResourceTest extends TestCase { + + /** + * Loads an existing resource from the class path. Verifies it is found. + * + */ + public void testResourceFound() throws IOException { + ClassPathResource resource = new ClassPathResource( + "org/wamblee/io/myresource.txt"); + InputStream is = resource.getInputStream(); + String data = FileSystemUtils.read(is); + assertEquals("This is my resource", data); + } + + /** + * Loads a non-existing resource from the class path. Verifies that an IO + * exception is thrown. + * + */ + public void testResourceNotFound() { + try { + ClassPathResource resource = new ClassPathResource( + "org/wamblee/io/myresource-nonexistent.txt"); + InputStream is = resource.getInputStream(); + } catch (IOException e) { + return; // ok + } + fail(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java new file mode 100644 index 00000000..12db916e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java @@ -0,0 +1,122 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import static org.mockito.Mockito.*; +import junit.framework.TestCase; + +import org.apache.oro.io.AwkFilenameFilter; + +public class DirectoryMonitorTest extends TestCase { + + private static final String REGEX = "^.*\\.txt$"; + private static final String FILE1 = "file1.txt"; + + private TestData _data; + private DirectoryMonitor.Listener _listener; + + private DirectoryMonitor _monitor; + + @Override + protected void setUp() throws Exception { + super.setUp(); + _data = new TestData(this); + _data.clean(); + _listener = mock(DirectoryMonitor.Listener.class); + _monitor = new DirectoryMonitor(_data.getRoot(), new AwkFilenameFilter( + REGEX), _listener); + } + + public void testEmptyDir() { + // Nothing is expected to be called. + for (int i = 0; i < 10; i++) { + _monitor.poll(); + verifyNoMoreInteractions(_listener); + } + } + + public void testFileCreated() { + _data.createFile(FILE1, "hello"); + _monitor.poll(); + verify(_listener).fileCreated(_data.getFile(FILE1)); + } + + public void testFileDeleted() { + _data.createFile(FILE1, "hello"); + _monitor.poll(); + reset(_listener); + + _data.deleteFile(FILE1); + _monitor.poll(); + + verify(_listener).fileDeleted(_data.getFile(FILE1)); + verifyNoMoreInteractions(_listener); + } + + public void testFileChanged() throws InterruptedException { + _data.createFile(FILE1, "hello"); + _monitor.poll(); + reset(_listener); + + Thread.sleep(2000); + _data.deleteFile(FILE1); + _data.createFile(FILE1, "bla"); + + _monitor.poll(); + verify(_listener).fileChanged(_data.getFile(FILE1)); + verifyNoMoreInteractions(_listener); + } + + public void testFileFilterIsUsed() { + _monitor.poll(); + + _data.createFile("file.xml", "hello"); + _monitor.poll(); + verifyNoMoreInteractions(_listener); + } + + public void testDirectoryIsIgnored() { + _monitor.poll(); + _data.createDir(FILE1); + _monitor.poll(); + verifyNoMoreInteractions(_listener); + } + + public void testExceptionsWIllLeadToRepeatedNotifications() { + _monitor.poll(); + _data.createFile(FILE1, "hello"); + + stubVoid(_listener).toThrow(new RuntimeException()).on(). + fileCreated(_data.getFile(FILE1)); + + try { + _monitor.poll(); + } catch (RuntimeException e) { + reset(_listener); + + // polling again should lead to the same filecreated call. + // this time no exception is thrown. + + _monitor.poll(); + verify(_listener).fileCreated(_data.getFile(FILE1)); + verifyNoMoreInteractions(_listener); + return; + } + fail(); // should not get here. + + + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java new file mode 100644 index 00000000..4f301cf7 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/DirectoryMonitorTestProgram.java @@ -0,0 +1,51 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.io; + +import java.io.File; + +import org.apache.oro.io.AwkFilenameFilter; + +/** + * + * + * @author Erik Brakkee + */ +public class DirectoryMonitorTestProgram { + + public static void main(String[] aArgs) throws Exception { + + DirectoryMonitor monitor = new DirectoryMonitor(new File("."), + new AwkFilenameFilter(".*\\.txt"), new DirectoryMonitor.Listener() { + public void fileChanged(File aFile) { + System.out.println("changed " + aFile); + } + public void fileCreated(File aFile) { + System.out.println("created " + aFile); + } + public void fileDeleted(File aFile) { + System.out.println("deleted " + aFile); + } + }); + + for (;;) { + monitor.poll(); + Thread.sleep(1000); + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/FileResourceTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/FileResourceTest.java new file mode 100644 index 00000000..c1564f04 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/FileResourceTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.io; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + + +import junit.framework.TestCase; + +/** + * Tests the file resource. + * + * @author Erik Brakkee + */ +public class FileResourceTest extends TestCase { + + /** + * Loads an existing resource. Verifies it is found. + * + */ + public void testResourceFound() throws IOException { + FileResource resource = new FileResource( new File( + FileSystemUtils.getTestInputDir(FileResourceTest.class), + "myresource.txt")); + InputStream is = resource.getInputStream(); + String data = FileSystemUtils.read(is); + assertEquals("This is my resource", data); + } + + /** + * Loads a non-existing resource. Verifies that an IO + * exception is thrown. + * + */ + public void testResourceNotFound() { + try { + FileResource resource = new FileResource( new File( + FileSystemUtils.getTestInputDir(FileResourceTest.class), + "myresource-nonexistent.txt")); + InputStream is = resource.getInputStream(); + } catch (IOException e) { + return; // ok + } + fail(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java new file mode 100644 index 00000000..ad3b4e20 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/FileSystemUtils.java @@ -0,0 +1,369 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLDecoder; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.security.CodeSource; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * File system utilities. + * + * @author Erik Brakkee + */ +public final class FileSystemUtils { + + private static final Log LOG = LogFactory.getLog(FileSystemUtils.class); + + /** + * Test output directory relative to the sub project. + */ + private static final String TEST_OUTPUT_DIR = "../target/testoutput"; + + /** + * Test input directory relative to the sub project. + */ + private static final String TEST_INPUT_DIR = "../src/test/resources"; + + /* + * Disabled. + * + */ + private FileSystemUtils() { + // Empty + } + + /** + * Deletes a directory recursively. The test case will fail if the directory + * does not exist or if deletion fails. + * + * @param aDir + * Directory to delete. + */ + public static void deleteDirRecursively(String aDir) { + deleteDirRecursively(new File(aDir)); + } + + /** + * Deletes a directory recursively. See {@link #deleteDirRecursively}. + * + * @param aDir + * Directory. + */ + public static void deleteDirRecursively(File aDir) { + TestCase.assertTrue(aDir.isDirectory()); + + for (File file : aDir.listFiles()) { + if (file.isDirectory()) { + deleteDirRecursively(file); + } else { + delete(file); + } + } + + delete(aDir); + } + + /** + * Deletes a file or directory. The test case will fail if the file or + * directory does not exist or if deletion fails. Deletion of a non-empty + * directory will always fail. + * + * @param aFile + * File or directory to delete. + */ + public static void delete(File aFile) { + TestCase.assertTrue(aFile.delete()); + } + + /** + * Gets a path relative to a sub project. This utility should be used to + * easily access file paths within a subproject without requiring any + * specific Eclipse configuration. + * + * @param aRelativePath + * Relative path. + * @param aTestClass + * Test class. + */ + public static File getPath(String aRelativePath, Class aTestClass) { + CodeSource source = aTestClass.getProtectionDomain().getCodeSource(); + if (source == null) { + LOG.warn("Could not obtain path for '" + aRelativePath + + "' for class " + aTestClass + + ", using relative path as is"); + return new File(aRelativePath); + } + URL location = source.getLocation(); + String protocol = location.getProtocol(); + if (!protocol.equals("file")) { + LOG.warn("protocol is not 'file': " + location); + return new File(aRelativePath); + } + + String path = location.getPath(); + try { + path = URLDecoder.decode(location.getPath(), "UTF-8"); + } catch (UnsupportedEncodingException e) { + // ignore it.. just don't decode + LOG.warn("Decoding path failed: '" + location.getPath() + "'", e); + } + + return new File(new File(path).getParentFile(), aRelativePath); + } + + /** + * Ensures that a directory hierarchy exists (recursively if needed). If it + * is not possible to create the directory, then the test case will fail. + * + * @param aDir + * Directory to create. + */ + public static void createDir(File aDir) { + if (aDir.exists() && !aDir.isDirectory()) { + TestCase.fail("'" + aDir + + "' already exists and is not a directory"); + } + if (aDir.exists()) { + return; + } + createDir(aDir.getParentFile()); + TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir()); + } + + /** + * Creates a file in a directory. + * @param aDir Directory path. Will be created if it does not exist. + * @param aName Filename. + * @param aContents Contents. + */ + public static void createFile(File aDir, String aName, InputStream aContents) { + createDir(aDir); + try { + OutputStream os = new FileOutputStream(new File(aDir, aName)); + copyStream(aContents, os); + } catch (IOException e) { + e.printStackTrace(); + TestCase.fail(e.getMessage()); + } + } + + /** + * Gets the test output directory for a specific test class. + * + * @param aTestClass + * Test class. + * @return Test output directory. + */ + public static File getTestOutputDir(Class aTestClass) { + File file = getPath(TEST_OUTPUT_DIR, aTestClass); + String className = aTestClass.getName(); + String classRelPath = className.replaceAll("\\.", "/"); + return new File(file, classRelPath); + } + + /** + * Gets the test input directory for a specific test class. + * + * @param aTestClass + * Test class. + * @return Test input directory. + */ + public static File getTestInputDir(Class aTestClass) { + File file = getPath(TEST_INPUT_DIR, aTestClass); + String packageName = aTestClass.getPackage().getName(); + String packagePath = packageName.replaceAll("\\.", "/"); + return new File(file, packagePath); + } + + /** + * Creates a directory hierarchy for the output directory of a test class if + * needed. + * + * @param aTestClass + * Test class + * @return Test directory. + */ + public static File createTestOutputDir(Class aTestClass) { + File file = getTestOutputDir(aTestClass); + createDir(file); + return file; + } + + /** + * Gets a test output file name. This returns a File object representing the + * output file and ensures that the directory where the file will be created + * already exists. + * + * @param aName + * Name of the file. + * @param aTestClass + * Test class. + * @return File. + */ + public static File getTestOutputFile(String aName, Class aTestClass) { + File file = new File(getTestOutputDir(aTestClass), aName); + createDir(file.getParentFile()); + return file; + } + + public static String read(InputStream aIs) throws IOException { + try { + StringBuffer buffer = new StringBuffer(); + int c; + while ((c = aIs.read()) != -1) { + buffer.append((char) c); + } + return buffer.toString(); + } finally { + aIs.close(); + } + } + + /** + * Copies an input stream to an output stream. + * + * @param aIs + * Input stream. + * @param aOs + * Output stream. + */ + public static void copyStream(InputStream aIs, OutputStream aOs) { + try { + int c; + while ((c = aIs.read()) != -1) { + aOs.write(c); + } + aIs.close(); + aOs.close(); + } catch (IOException e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } + + /** + * Recursively copy a directory. + * + * @param aSrc + * Source directory + * @param aTarget + * Target directory. + */ + public static void copyDir(File aSrc, File aTarget) { + Assert.assertTrue(aSrc.isDirectory()); + Assert.assertTrue(!aTarget.exists()); + + aTarget.mkdirs(); + + File[] files = aSrc.listFiles(); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (file.isDirectory()) { + if (!file.getName().equals(".svn")) { + copyDir(new File(aSrc, file.getName()), new File(aTarget, + file.getName())); + } + } else { + copyFile(file, new File(aTarget, file.getName())); + } + } + } + + /** + * Copy a file. If copying fails then the testcase will fail. + * + * @param aSrc + * Source file. + * @param aTarget + * Target file. + */ + public static void copyFile(File aSrc, File aTarget) { + + try { + FileInputStream fis = new FileInputStream(aSrc); + FileOutputStream fos = new FileOutputStream(aTarget); + FileChannel fcin = fis.getChannel(); + FileChannel fcout = fos.getChannel(); + + // map input file + + MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0, + fcin.size()); + + // do the file copy + fcout.write(mbb); + + // finish up + + fcin.close(); + fcout.close(); + fis.close(); + fos.close(); + } catch (IOException e) { + Assert.assertTrue("Copying file " + aSrc.getPath() + " to " + + aTarget.getPath() + " failed.", false); + } + } + + /** + * Remove all files within a given directory including the directory itself. + * This only attempts to remove regular files and not directories within the + * directory. If the directory contains a nested directory, the deletion + * will fail. The test case will fail if this fails. + * + * @param aDir + * Directory to remove. + */ + public static void deleteDir(File aDir) { + cleanDir(aDir); + delete(aDir); + } + + /** + * Remove all regular files within a given directory. + * + * @param outputDirName + */ + public static void cleanDir(File aDir) { + if (!aDir.exists()) { + return; // nothing to do. + } + File[] entries = aDir.listFiles(); + for (int i = 0; i < entries.length; i++) { + File file = entries[i]; + if (file.isFile()) { + Assert.assertTrue("Could not delete " + entries[i].getPath(), + entries[i].delete()); + } + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java new file mode 100644 index 00000000..1cf9478f --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/StreamResourceTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.io; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + + +import junit.framework.TestCase; + +/** + * Tests the stream resource. + * + * @author Erik Brakkee + */ +public class StreamResourceTest extends TestCase { + + /** + * Loads an existing resource. Verifies it is found. + * + */ + public void testResourceFound() throws IOException { + File file = new File( + FileSystemUtils.getTestInputDir(StreamResourceTest.class), + "myresource.txt"); + assertTrue(file.canRead()); + InputStream fileIs = new FileInputStream(file); + InputResource resource = new StreamResource(fileIs); + InputStream is = resource.getInputStream(); + String data = FileSystemUtils.read(is); + assertEquals("This is my resource", data); + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/TestData.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/TestData.java new file mode 100644 index 00000000..58bea68e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/TestData.java @@ -0,0 +1,191 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.io; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; + +import junit.framework.Assert; + +/** + * TestData provides a convenient interface for managing test output files. + * + * @author Erik Brakkee + */ +public final class TestData { + + private Object _testcase; + private File _root; + + /** + * Test data to be constructed in the setUp of a test. {@link #clean()} must + * be called to make sure that this directory is empty before executing a + * test. + */ + public TestData(Object aTestcase) { + _testcase = aTestcase; + _root = getTestRootDir(aTestcase); + FileSystemUtils.createDir(_root); + } + + /** + * Obtain root directory of JUnit tests. + * + * @return Directory name. + */ + private static File getTestRootDir(Object aTestcase) { + return FileSystemUtils.getTestOutputDir(aTestcase.getClass()); + } + + public void createFile(String aRelative, String aFile, InputStream aContents) { + FileSystemUtils + .createFile(new File(_root, aRelative), aFile, aContents); + } + + public void createFile(String aFile, String aContents) { + createFile(".", aFile, aContents); + } + + public void createFile(String aRelative, String aFile, String aContents) { + InputStream is = new ByteArrayInputStream(aContents.getBytes()); + FileSystemUtils.createFile(new File(_root, aRelative), aFile, is); + } + + public void deleteFile(String aFile) { + deleteFile(".", aFile); + } + + public void deleteFile(String aRelative, String aFile) { + FileSystemUtils.delete(new File(_root, aFile)); + } + + /** + * Returns a temporary directory. + * + * @return Temporary directory. + */ + public File getTmpDir() { + return new File(_root, "tmpdir"); + } + + /** + * Cleans up the test output directory. + */ + public void clean() { + FileSystemUtils.deleteDirRecursively(_root); + FileSystemUtils.createDir(_root); + } + + /** + * Recursively copy a directory contents to the test output directory. + * + * @param sSrc + * Source directory to copy. + */ + public void copyDir(File aSrc) { + FileSystemUtils.copyDir(aSrc, _root); + } + + /** + * Copies a classpath resource to a relative path in the test output + * directory. + * + * @param aResource + * Resource to copy. + * @param aRelativePath + * Relative path. + */ + public void copyResource(String aResource, String aRelativePath) { + try { + InputStream is = new ClassPathResource(aResource).getInputStream(); + FileOutputStream fos = new FileOutputStream(new File(_root, + aRelativePath)); + FileSystemUtils.copyStream(is, fos); + } catch (IOException e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } + + /** + * Copies a resource to the root directory of the test output. + * + * @param aResource + * Resource. + */ + public void copyResource(String aResource) { + String basename = new File(aResource).getName(); + copyResource(aResource, basename); + } + + public void createDir(String aRelative) { + FileSystemUtils.createDir(new File(_root, aRelative)); + } + + /** + * Deletes a file or directory relative to the test output root. + * + * @param aRelative + * Relative path. The testcase will fail if the file or directory + * cannot be removed. + */ + public void delete(String aRelative) { + FileSystemUtils.delete(new File(_root, aRelative)); + } + + /** + * Deletes a directory including its contents. + * + * @param aRelative + * Relative path. + */ + public void deleteDir(String aRelative) { + FileSystemUtils.deleteDir(new File(_root, aRelative)); + } + + /** + * Deletes a directory recursively. + * + * @param aRelative + * Relative path. + */ + public void deleteDirRecursively(String aRelative) { + FileSystemUtils.deleteDir(new File(_root, aRelative)); + } + + /** + * Gets the root of the test output directory. + * + * @return Root of the test output. + */ + public File getRoot() { + return _root; + } + + /** + * Gets a file object for a relative path. + */ + public File getFile(String aRelative) { + return new File(_root, aRelative); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/TestResource.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/TestResource.java new file mode 100644 index 00000000..ec28290f --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/io/TestResource.java @@ -0,0 +1,47 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.io; + +import java.io.File; + + +/** + * Test resource for locating resources in the classpath. + */ +public class TestResource extends FileResource { + + /** + * Test class name. + * @param aTestClass Test class. + * @param aName Name of the file to look for. + */ + public TestResource(Class aTestClass, String aName) { + super(getFile(aTestClass, aName)); + } + + /** + * Computes the file path of the file to look for. + * @param aClass Test class name. + * @param aName Name of the file. + * @return File. + */ + private static File getFile(Class aClass, String aName) { + File dir = FileSystemUtils.getTestInputDir(aClass); + return new File(dir, aName); + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/observer/ObservableTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/observer/ObservableTest.java new file mode 100644 index 00000000..8a060e89 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/observer/ObservableTest.java @@ -0,0 +1,143 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.observer; + +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.List; + +import org.mockito.InOrder; + +import junit.framework.TestCase; + +/** + * Test of the observer pattern implementation. + * + * @author Erik Brakkee + */ +public class ObservableTest extends TestCase { + + private static final int SUBSCRIBER_COUNT = 100; + + private static final String UPDATE = "send"; + + private Integer _observed; + private Observable _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(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/AssertionUtils.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/AssertionUtils.java new file mode 100644 index 00000000..a0216a8b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/AssertionUtils.java @@ -0,0 +1,156 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.test; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Useful assertions for use in test cases. + * + * @author Erik Brakkee + */ +public final class AssertionUtils { + + private static final Log LOG = LogFactory.getLog(AssertionUtils.class); + + /** + * Disabled constructor. + * + */ + private AssertionUtils() { + // Empty + } + + /** + * Asserts that two object arrays are equal. + * + * @param aExpected + * Expected object array. + * @param aActual + * Actual object array. + */ + public static void assertEquals(T[] aExpected, T[] aActual) { + assertEquals("", aExpected, aActual); + } + + + /** + * Asserts that two object arrays are equal. + * + * @param aMsg + * Message. + * @param aExpected + * Expected array. + * @param aActual + * Actual array. + */ + public static void assertEquals(String aMsg, T[] aExpected, + T[] aActual) { + TestCase.assertEquals(aMsg + " expected " + + Arrays.asList(aExpected) + ", actual " + + Arrays.asList(aActual) + ": Array lengths ", aExpected.length, + aActual.length); + + for (int i = 0; i < aExpected.length; i++) { + TestCase.assertEquals(aMsg + ": Element " + i, aExpected[i], + aActual[i]); + } + } + + + /** + * Asserts that two objects are equal, and in case the object is an Object[] + * delegates to {@link #assertEquals(String, Object[], Object[]). + * + * @param aMsg + * Message. + * @param aExpected + * Expected result. + * @param aActual + * Actual result. + */ + public static void assertEquals(String aMsg, T aExpected, + T aActual) { + if (aExpected instanceof Object[]) { + AssertionUtils.assertEquals(aMsg, (Object[]) aExpected, + (Object[]) aActual); + + return; + } + + TestCase.assertEquals(aMsg, aExpected, aActual); + } + + /** + * Asserts that two maps are equal by comparing all keys and by checking + * that the values for the same keys are the same. + * + * @param aMsg + * Message. + * @param aExpectedMap + * Expected result. + * @param aActual + * Actual result. + */ + public static 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)); + AssertionUtils.assertEquals("Value of key " + key + " of map", + aExpectedMap.get(key), aActual.get(key)); + } + } + + public static interface ErroneousCode { + void run() throws Exception; + } + + /** + * Asserts that an exception occurs. + * @param aRunnable Test cases should create a subclass of this which contains the + * code that should throw an exception. + * @param aType Type of exception that is expected. + */ + public static void assertException(ErroneousCode aObject, Class aType) { + try { + aObject.run(); + throw new RuntimeException("No exception occurred"); + } catch (Throwable t) { + if ( aType.isInstance(t)) { + LOG.info("Expected exception occured " + t.getMessage()); + return; // ok + } + else { + throw new RuntimeException(t); + } + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/EventTracker.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/EventTracker.java new file mode 100644 index 00000000..333da1e7 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/EventTracker.java @@ -0,0 +1,146 @@ +/* + * Copyright 2006 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Tracks the occurence of certain events in a test environment. Threads in a + * test environment tell the event tracker of the occurrence of certain events + * using {@link #eventOccurred(Event)}. Test code inspects the events sent by a + * thread using {@link #isEventSent(Thread, Event)}. + * + * A record is kept of every event which is sent. Therefore, the occurrence of a + * new event does not erase a previously sent event. + * + * @param + * Type of event sent from test code. Usually String will be + * sufficient. The event type must provide a sensible implementation + * of {@link java.lang.Object#equals(java.lang.Object)}. + * + * @author Erik Brakkee + */ +public class EventTracker { + + private static final Log LOG = LogFactory.getLog(EventTracker.class); + + /** + * Map of Thread object to a list of events. + */ + private Map> _events; + + /** + * Constructs the event tracker. + * + */ + public EventTracker() { + clear(); + } + + 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 events = _events.get(current); + if (events == null) { + events = new ArrayList(); + _events.put(current, events); + } + events.add(aEvent); + } + + /** + * Checks if a specific event has happened in a specific thread. + * + * @param aThread + * Thread to check. + * @param aEvent + * Event to check for. + * @return Whether or not the event was sent. + */ + public synchronized boolean isEventSent(Thread aThread, Event aEvent) { + List events = _events.get(aThread); + if (events == null) { + return false; + } + return events.contains(aEvent); + } + + /** + * Gets the events for a thread in the order they were sent + * + * @param aThread + * Thread to get events for. + * @return Events that were sent. A zero-sized array is returned if no + * events were sent. + */ + public synchronized List getEvents(Thread aThread) { + List events = _events.get(aThread); + if (events == null) { + events = Collections.emptyList(); + } + return Collections.unmodifiableList(events); + } + + /** + * Gets the number of times an event was sent summed up + * over all threads. + * + * @param aEvent + * Event to check. + * @return Number of times it was reached. + */ + public synchronized int getEventCount(Event aEvent) { + int count = 0; + for (Thread thread : _events.keySet()) { + List events = _events.get(thread); + for (Event event : events) { + if (event.equals(aEvent)) { + count++; + } + } + } + return count; + } + + /** + * Gets the total event count over all threads. + * @return + */ + public synchronized int getEventCount() { + int count = 0; + for (Thread thread: _events.keySet()) { + count += _events.get(thread).size(); + } + return count; + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/TimingUtils.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/TimingUtils.java new file mode 100644 index 00000000..82d3c0e8 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/test/TimingUtils.java @@ -0,0 +1,48 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.test; + +import junit.framework.TestCase; + +/** + * Timing utilities. + * + * @author Erik Brakkee + */ +public final class TimingUtils { + + /** + * Disabled constructor. + * + */ + private TimingUtils() { + // Empty + } + + /** + * Sleeps for a time. + * @param aMillis Number of milliseconds to sleep. + */ + public static void sleep(int aMillis) { + try { + Thread.sleep(aMillis); + } catch (InterruptedException e) { + TestCase.fail("Who interrupted my sleep?"); + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java new file mode 100644 index 00000000..39280c60 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/ClasspathUriResolverTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.xml; + +import java.io.IOException; + +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.URIResolver; +import javax.xml.transform.stream.StreamSource; + +import junit.framework.TestCase; + + +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.FileSystemUtils; + +/** + * Tests for {@link org.wamblee.xml.ClasspathUriResolver}. + * + * @author Erik Brakkee + */ +public class ClasspathUriResolverTest extends TestCase { + + private URIResolver _resolver; + + /* (non-Javadoc) + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + _resolver = new ClasspathUriResolver(); + } + + /** + * Resolves an existing file. Verifies the file is resolved correctly. + * @throws TransformerException + * @throws IOException + */ + public void testResolveExistingFile() throws TransformerException, IOException { + Source source = _resolver.resolve("org/wamblee/xml/reportToHtml.xsl", ""); + assertTrue(source instanceof StreamSource); + String resolved = FileSystemUtils.read(((StreamSource)source).getInputStream()); + + ClassPathResource resource = new ClassPathResource("org/wamblee/xml/reportToHtml.xsl"); + String expected = FileSystemUtils.read(resource.getInputStream()); + assertEquals(expected, resolved); + } + + /** + * Resolves a non-existing file. Verifies that a TransformerException is thrown. + * + */ + public void testResolveNonExistingFile() { + try { + Source source = _resolver.resolve("org/wamblee/xml/reportToHtml-nonexisting.xsl", ""); + } catch (TransformerException e) { + return; // ok + } + fail(); + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/XmlUtils.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/XmlUtils.java new file mode 100644 index 00000000..fc894251 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/XmlUtils.java @@ -0,0 +1,162 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.xml; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import junit.framework.TestCase; + +import org.dom4j.Attribute; +import org.dom4j.Document; +import org.dom4j.Element; + +/** + * XML test support utilities. + * + * @author Erik Brakkee + */ +public final class XmlUtils { + + /** + * Disabled constructor. + * + */ + private XmlUtils() { + // Empty + } + + /** + * Checks equality of two XML documents excluding comment and processing + * nodes and trimming the text of the elements. In case of problems, it + * provides an xpath-like expression describing where the problem is. + * + * @param aMsg + * @param aExpected + * @param aActual + */ + public static void assertEquals(String aMsg, + org.w3c.dom.Document aExpected, org.w3c.dom.Document aActual) { + assertEquals(aMsg, DomUtils.convert(aExpected), DomUtils + .convert(aActual)); + } + + /** + * Checks equality of two XML documents excluding comment and processing + * nodes and trimming the text of the elements. In case of problems, it + * provides an xpath-like expression describing where the problem is. + * + * @param aMsg + * @param aExpected + * @param aActual + */ + public static void assertEquals(String aMsg, Document aExpected, + Document aActual) { + assertEquals(aMsg + "/" + aExpected.getRootElement().getName(), aExpected.getRootElement(), aActual.getRootElement()); + } + + /** + * Checks equality of two XML elements excluding comment and processing + * nodes and trimming the text of the elements. In case of problems, it + * provides an xpath-like expression describing where the problem is. + * + * @param aMsg + * @param aExpected + * @param aActual + */ + public static void assertEquals(String aMsg, Element aExpected, + Element aActual) { + + // Name. + TestCase.assertEquals(aMsg + "/name()", aExpected.getName(), aActual + .getName()); + + // Text + TestCase.assertEquals(aMsg + "/text()", aExpected.getTextTrim(), + aActual.getTextTrim()); + + // Attributes + List 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()); + for (int i = 0; i < expectedAttrs.size(); i++) { + String msg = aMsg + "/@" + expectedAttrs.get(i).getName(); + assertEquals(msg, expectedAttrs.get(i), actualAttrs.get(i)); + } + + // Nested elements. + List expectedElems = aExpected.elements(); + List actualElems = aActual.elements(); + TestCase.assertEquals("count(" + aMsg + "/*)", expectedElems.size(), + actualElems.size()); + // determine the how-manyth element of the given name we are at. + // Maps element name to the last used index (or null if not yet used) + Map 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 + "]"; + + assertEquals(msg, expectedElems.get(i), actualElems.get(i)); + } + } + + /** + * Checks equality of two attributes. In case of problems, it + * provides an xpath-like expression describing where the problem is. + * + * @param aMsg + * @param aExpected + * @param aActual + */ + public static void assertEquals(String aMsg, Attribute aExpected, + Attribute aActual) { + TestCase.assertEquals(aMsg + ":name", aExpected.getName(), aActual + .getName()); + TestCase.assertEquals(aMsg + ":value", aExpected.getValue(), aActual + .getValue()); + } + + /** + * Comparator which compares attributes by name. + */ + private static final class AttributeComparator implements + Comparator { + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(T, T) + */ + public int compare(Attribute aAttribute1, Attribute aAttribute2) { + return aAttribute1.getName().compareTo(aAttribute2.getName()); + } + } +} diff --git a/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java new file mode 100644 index 00000000..d30e60a6 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/java/org/wamblee/xml/XslTransformerTest.java @@ -0,0 +1,257 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.xml; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; + +import junit.framework.TestCase; +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.FileSystemUtils; +import org.wamblee.io.InputResource; + +import org.w3c.dom.Document; + +/** + * Tests the XSL transformer. + * + * @author Erik Brakkee + */ +public class XslTransformerTest extends TestCase { + + private static final String INCLUDED_XSL_FILE = "utilities.xsl"; + + private static final String REPORT_XML = "report.xml"; + + private static final String REPORT_TO_HTML_XSLT = "reportToHtml.xsl"; + + private static final String REPORT_TO_HTML2_XSLT = "reportToHtml2.xsl"; + + private static final String REPORT_TO_HTML_INVALID_XSLT = "reportToHtml-invalid.xsl"; + + private static final String REPORT_TO_HTML_NONWELLFORMED_XSLT = "reportToHtml-nonwellformed.xsl"; + + private static final String REPORT_TO_TEXT_XSLT = "reportToText.xsl"; + + private String getResourcePath(String aResource) { + return getClass().getPackage().getName().replaceAll("\\.", "/") + "/" + aResource; + } + + /** + * Transforms a file while using the default resolver, where the included + * file can be found. Verifies the transformation is done correctly. + * + */ + public void testTransformUsingDefaultResolver() throws Exception { + XslTransformer transformer = new XslTransformer(); + + InputResource xmlResource = new ClassPathResource(getResourcePath(REPORT_XML)); + + Source xslt = new StreamSource(new ClassPathResource(getResourcePath( + REPORT_TO_HTML_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils + .read(xmlResource.getInputStream()).getBytes(); + DocumentBuilder builder = DocumentBuilderFactory.newInstance() + .newDocumentBuilder(); + Document document = builder.parse(xmlResource.getInputStream()); + Source documentSource = new StreamSource(xmlResource.getInputStream()); + + Document expected = DomUtils.read(new ClassPathResource(getResourcePath( + "output-reportToHtml-report.xml")).getInputStream()); + + Document output1 = transformer.transform(documentData, xslt); + XmlUtils.assertEquals("byte[] transform", expected, output1); + + xslt = new StreamSource(new ClassPathResource(getResourcePath( + REPORT_TO_HTML_XSLT)).getInputStream()); + Document output2 = transformer.transform(document, xslt); + XmlUtils.assertEquals("document transform", expected, output2); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Result output = new StreamResult(os); + + xslt = new StreamSource(new ClassPathResource(getResourcePath( + REPORT_TO_HTML_XSLT)).getInputStream()); + transformer.transform(documentSource, output, xslt); + XmlUtils.assertEquals("document source transform", expected, DomUtils + .read(os.toString())); + + xslt = new StreamSource(new ClassPathResource(getResourcePath( + REPORT_TO_HTML_XSLT)).getInputStream()); + String result = transformer.textTransform(documentData, xslt); + XmlUtils + .assertEquals("text transform", expected, DomUtils.read(result)); + } + + /** + * Transforms a file using the default resolver where the included file + * cannot be found. Verifies that a TransformerException is thrown. + * + */ + public void testTransformUsingDefaultResolverFails() throws IOException { + XslTransformer transformer = new XslTransformer(); + + InputResource xmlResource = + new ClassPathResource(getResourcePath(REPORT_XML)); + Source xslt = new StreamSource( + new ClassPathResource(getResourcePath( + REPORT_TO_HTML2_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils + .read(xmlResource.getInputStream()).getBytes(); + try { + Document output1 = transformer.transform(documentData, xslt); + } catch (TransformerException e) { + return; // ok + } + fail(); + } + + /** + * Transforms a file using an invalid Xslt. Verifies that a + * TransformerException is thrown. + * + */ + public void testTransformInvalidXslt() throws IOException { + XslTransformer transformer = new XslTransformer(); + + InputResource xmlResource = new ClassPathResource( + getResourcePath(REPORT_XML)); + Source xslt = new StreamSource( + new ClassPathResource(getResourcePath(REPORT_TO_HTML_INVALID_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils + .read(xmlResource.getInputStream()).getBytes(); + try { + Document output1 = transformer.transform(documentData, xslt); + } catch (TransformerException e) { + return; // ok + } + fail(); + } + + /** + * Transforms a file using a non-well formed xslt. Verifies that a + * TransformerException is thrown. + * + */ + public void testTransformNonWellformedXslt() throws IOException { + XslTransformer transformer = new XslTransformer(); + + InputResource xmlResource = new ClassPathResource( + getResourcePath(REPORT_XML)); + Source xslt = new StreamSource( + new ClassPathResource(getResourcePath( + REPORT_TO_HTML_NONWELLFORMED_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils + .read(xmlResource.getInputStream()).getBytes(); + try { + Document output1 = transformer.transform(documentData, xslt); + } catch (TransformerException e) { + return; // ok + } + fail(); + } + + /** + * Transforms a file using a class path resolver. + * + */ + public void testTransformUsingClassPathResolver() throws Exception { + XslTransformer transformer = new XslTransformer(new ClasspathUriResolver()); + + InputResource xmlResource = new ClassPathResource(getResourcePath( + REPORT_XML)); + Source xslt = new StreamSource(new ClassPathResource( + getResourcePath(REPORT_TO_HTML2_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils + .read(xmlResource.getInputStream()).getBytes(); + + Document output1 = transformer.transform(documentData, xslt); + Document expected = DomUtils.read(new ClassPathResource( + getResourcePath("output-reportToHtml-report.xml")) + .getInputStream()); + XmlUtils.assertEquals("doc", expected, output1); + } + + /** + * Transforms a file to text output. Verifies the file is transformed + * correctly. + * + */ + public void testTransformToTextOutput() throws Exception { + XslTransformer transformer = new XslTransformer(new ClasspathUriResolver()); + + InputResource xmlResource = new ClassPathResource( + getResourcePath(REPORT_XML)); + Source xslt = new StreamSource( + new ClassPathResource(getResourcePath(REPORT_TO_TEXT_XSLT)).getInputStream()); + + byte[] documentData = FileSystemUtils + .read(xmlResource.getInputStream()).getBytes(); + + String result = transformer.textTransform(documentData, xslt); + String expected = "Hello world!"; + assertEquals("text transform", expected, result); + } + + /** + * Tests resolving a file using {@link XslTransformer#resolve(String)} with the + * default resolver where the file does not exist. + * + */ + public void testResolveWithDefaultResolverFileNotFound() { + XslTransformer transformer = new XslTransformer(); + try { + Source source = transformer.resolve("org/wamblee/xml/utilities-nonexistent.xsl"); + } catch (TransformerException e) { + return; // ok + } + fail(); + } + + + /** + * Tests resolving a file using {@link XslTransformer#resolve(String)} with the + * default resolver. + * + */ + public void testResolveWithClasspathResolver() throws Exception { + XslTransformer transformer = new XslTransformer(new ClasspathUriResolver()); + Source source = transformer.resolve(getResourcePath(INCLUDED_XSL_FILE)); + assert(source instanceof StreamSource); + StreamSource ssource = (StreamSource)source; + String data = FileSystemUtils.read(ssource.getInputStream()); + String expected = FileSystemUtils.read(new ClassPathResource(getResourcePath(INCLUDED_XSL_FILE)).getInputStream()); + assertEquals(expected, data); + } + +} + + diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/cache/ehcache.xml b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/cache/ehcache.xml new file mode 100644 index 00000000..694184ed --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/cache/ehcache.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beanRefContext.xml b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beanRefContext.xml new file mode 100644 index 00000000..a453f3de --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beanRefContext.xml @@ -0,0 +1,15 @@ + + + + + + + + + org/wamblee/general/spring1.xml + + + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beankernel-wrong.properties b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beankernel-wrong.properties new file mode 100644 index 00000000..e54de19d --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beankernel-wrong.properties @@ -0,0 +1,2 @@ + +org.wamblee.beanfactory.class=org.wamblee.general.TestBeanFactoryBla diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beankernel.properties b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beankernel.properties new file mode 100644 index 00000000..e08cf398 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/beankernel.properties @@ -0,0 +1,2 @@ + +org.wamblee.beanfactory.class=org.wamblee.general.TestBeanFactory diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/spring1.xml b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/spring1.xml new file mode 100644 index 00000000..52ec0bec --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/general/spring1.xml @@ -0,0 +1,11 @@ + + + + + + + hello + + + \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/io/myresource.txt b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/io/myresource.txt new file mode 100644 index 00000000..c72f1105 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/io/myresource.txt @@ -0,0 +1 @@ +This is my resource \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/output-reportToHtml-report.xml b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/output-reportToHtml-report.xml new file mode 100644 index 00000000..40f29fd3 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/output-reportToHtml-report.xml @@ -0,0 +1,63 @@ + + + + KiSS crawler report + + +

KiSS crawler report

+

Successfully recorded programs

+ + + + + + + +
23:25 - 00:10: Wintertijd (Nederland + 1/Documentaire)
+
+ Some description MINSK - De presidentsverkiezingen + in Wit-Rusland zijn zondag met ruime cijfers gewonnen door + zittend president Aleksandr Loekasjenko. Dat bleek zondag uit + exitpolls uitgevoerd in opdracht van het totalitaire regime. Het + staatshoofd zou kunnen rekenen op ruim 82 procent van de + stemmen. Volgens de eerste gedeeltelijke uitslagen zou + Loekasjenko zelfs kunnen rekenen op bijna 89 procent. +
+
+
+

+

Possibly interesting programs

+

+ + + + + + + +
23:30 - 00:15: Brainiac (Discovery Channel/science)
+
+ Humor +
+
+
+

+

Category: horror

+

+ + + + + + + +
23:30 - 00:15: Andere tijden (Nederland 1/docu)
+
+ Documentaire +
+
+
+

+ + diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/report.xml b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/report.xml new file mode 100644 index 00000000..391aea94 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/report.xml @@ -0,0 +1,41 @@ + + + + Wintertijd + Some description MINSK - De presidentsverkiezingen in Wit-Rusland zijn zondag met ruime cijfers gewonnen door zittend president Aleksandr Loekasjenko. Dat bleek zondag uit exitpolls uitgevoerd in opdracht van het totalitaire regime. Het staatshoofd zou kunnen rekenen op ruim 82 procent van de stemmen. Volgens de eerste gedeeltelijke uitslagen zou Loekasjenko zelfs kunnen rekenen op bijna 89 procent. + Documentaire + Nederland 1 + + 23:25 + 00:10 + + + + + + + Brainiac + Humor + science + Discovery Channel + + 23:30 + 00:15 + + + + + Andere tijden + Documentaire + docu + Nederland 1 + + 23:30 + 00:15 + + + + + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml-invalid.xsl b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml-invalid.xsl new file mode 100644 index 00000000..104234e1 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml-invalid.xsl @@ -0,0 +1,99 @@ + + + + + + + + KiSS crawler report + + +

KiSS crawler report

+ + +

Possibly interesting programs

+ +
+ + No suitable programs found + + + + +
+ + +

+ + + +
+
+

+
+ + +

+ + + Successfully recorded programs + + + + Already recorded programs + + + + Conflicts with other recorded programs + + + + Programs that could not be recorded for + technical reasons. + + + +

+
+ + + + - : + + (/) + + + + +
+ + + +
+ + + + +
+ + + + + + + + + + + +

Category:

+ +
+
+ diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml-nonwellformed.xsl b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml-nonwellformed.xsl new file mode 100644 index 00000000..03d19083 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml-nonwellformed.xsl @@ -0,0 +1,99 @@ + + + + + + + + KiSS crawler report + + +

KiSS crawler report

+ + +

Possibly interesting programs

+ + + + No suitable programs found + + + + +
+ + +

+ + + +
+
+

+
+ + +

+ + + Successfully recorded programs + + + + Already recorded programs + + + + Conflicts with other recorded programs + + + + Programs that could not be recorded for + technical reasons. + + + +

+
+ + + + - : + + (/) + + + + +
+ + + +
+ + + + +
+ + + + + + + + + + + +

Category:

+ +
+
+ diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml.xsl b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml.xsl new file mode 100644 index 00000000..ce113d5a --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml.xsl @@ -0,0 +1,99 @@ + + + + + + + + KiSS crawler report + + +

KiSS crawler report

+ + +

Possibly interesting programs

+ +
+ + No suitable programs found + + + + +
+ + +

+ + + +
+
+

+
+ + +

+ + + Successfully recorded programs + + + + Already recorded programs + + + + Conflicts with other recorded programs + + + + Programs that could not be recorded for + technical reasons. + + + +

+
+ + + + - : + + (/) + + + + +
+ + + +
+ + + + +
+ + + + + + + + + + + +

Category:

+ +
+
+ diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml2.xsl b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml2.xsl new file mode 100644 index 00000000..2cec21fe --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToHtml2.xsl @@ -0,0 +1,101 @@ + + + + + + + + + + KiSS crawler report + + +

KiSS crawler report

+ + +

Possibly interesting programs

+ +
+ + No suitable programs found + + + + +
+ + +

+ + + +
+
+

+
+ + +

+ + + Successfully recorded programs + + + + Already recorded programs + + + + Conflicts with other recorded programs + + + + Programs that could not be recorded for + technical reasons. + + + +

+
+ + + + - : + + (/) + + + + +
+ + + +
+ + + + +
+ + + + + + + + + + + +

Category:

+ +
+
+ diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToText.xsl b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToText.xsl new file mode 100644 index 00000000..c1f7023c --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/reportToText.xsl @@ -0,0 +1,9 @@ + + + + + + Hello world! + + + diff --git a/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/utilities.xsl b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/utilities.xsl new file mode 100644 index 00000000..0dd7e62b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/general/src/test/resources/org/wamblee/xml/utilities.xsl @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/support/pom.xml b/tags/wamblee-utils-0.2/support/pom.xml new file mode 100644 index 00000000..c6d87fe6 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/pom.xml @@ -0,0 +1,21 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-support + pom + /support + http://wamblee.org + + + general + spring + + + diff --git a/tags/wamblee-utils-0.2/support/spring/pom.xml b/tags/wamblee-utils-0.2/support/spring/pom.xml new file mode 100644 index 00000000..ce6b4ae4 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/pom.xml @@ -0,0 +1,76 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-support-spring + jar + /support/spring + http://wamblee.org + + + org.wamblee + wamblee-support-general + 0.2 + + + org.wamblee + wamblee-support-general + 0.2 + test-jar + provided + + + org.springframework + spring-beans + + + org.springframework + spring-hibernate3 + + + org.hibernate + hibernate + + + + + org.wamblee + wamblee-hibernate-jpa + 0.2 + + + org.springframework + spring-aop + + + + log4j + log4j + + + dom4j + dom4j + + + net.sf.ehcache + ehcache + + + org.wamblee + wamblee-hibernate-jpa + 0.2 + + + jaxen + jaxen + + + + + diff --git a/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java new file mode 100644 index 00000000..61bd98ae --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/concurrency/spring/LockAdvice.java @@ -0,0 +1,55 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.concurrency.spring; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.wamblee.concurrency.Lock; + +/** + * Locking advice. This automatically synchronized an object using a given lock. + * + * @author Erik Brakkee + */ +public class LockAdvice implements MethodInterceptor { + + /** + * Lock to use. + */ + private Lock _lock; + + /** + * Constructs lock advice. + * @param aLock Lock to use. + */ + public LockAdvice(Lock aLock) { + _lock = aLock; + } + + /* (non-Javadoc) + * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation) + */ + public Object invoke(MethodInvocation aInvocation) throws Throwable { + _lock.acquire(); + try { + return aInvocation.proceed(); + } finally { + _lock.release(); + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java new file mode 100644 index 00000000..e01f0865 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/general/spring/SpringBeanFactory.java @@ -0,0 +1,98 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.general.spring; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.access.BeanFactoryLocator; +import org.springframework.beans.factory.access.BeanFactoryReference; +import org.springframework.context.access.ContextSingletonBeanFactoryLocator; +import org.wamblee.general.BeanFactory; +import org.wamblee.general.BeanFactoryException; +import org.wamblee.general.BeanKernel; + +/** + * Bean factory which uses Spring. This bean factory cannot be configured + * directly in the {@link org.wamblee.general.BeanKernel} because it does not + * provide a default no-arg constructor. Therefore, it must be delegated to or + * it must tbe subclassed to provide a default constructor. + */ +public class SpringBeanFactory implements BeanFactory { + + private BeanFactoryReference _factoryReference; + + /** + * Constructs the bean factory. + * + * @param aSelector + * Selector to find the appropriate bean ref context. + * @param aFactoryName + * Spring bean factory to use. + */ + public SpringBeanFactory(String aSelector, String aFactoryName) { + try { + BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator + .getInstance(aSelector); + _factoryReference = locator.useBeanFactory(aFactoryName); + } catch (BeansException e) { + throw new BeanFactoryException( + "Could not load bean factory: selector = '" + aSelector + + "', factory = '" + aFactoryName + "'", e); + } + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.general.BeanFactory#find(java.lang.String) + */ + public Object find(String aId) { + return find(aId, Object.class); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.general.BeanFactory#find(java.lang.Class) + */ + public T find(Class aClass) { + return find(aClass.getName(), aClass); + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.general.BeanFactory#find(java.lang.String, + * java.lang.Class) + */ + 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. + */ + public org.springframework.beans.factory.BeanFactory getSpringBeanFactory() { + return _factoryReference.getFactory(); + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java new file mode 100644 index 00000000..003395d3 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateMappingFiles.java @@ -0,0 +1,46 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.persistence.hibernate; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * Hibernate mapping files to use. + * + * @author Erik Brakkee + */ +public class HibernateMappingFiles extends ArrayList { + + /** + * Constructs an empty list of hibernate mapping files. + * + */ + public HibernateMappingFiles() { + super(); + } + + /** + * Constructs the list of Spring config files. + * @param aFiles Files. + */ + public HibernateMappingFiles(String[] aFiles) { + super(); + addAll(Arrays.asList(aFiles)); + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java new file mode 100644 index 00000000..8425facd --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/HibernateSupport.java @@ -0,0 +1,281 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.persistence.hibernate; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.wamblee.persistence.Persistent; + +/** + * Extension of + * {@link org.springframework.orm.hibernate.support.HibernateDaoSupport}. + * + * @author Erik Brakkee + */ +public class HibernateSupport extends HibernateDaoSupport { + + private static final Log LOG = LogFactory.getLog(HibernateSupport.class); + + /** + * This class provided an equality operation based on the object reference + * of the wrapped object. This is required because we cannto assume that the + * equals operation has any meaning for different types of persistent + * objects. This allows us to use the standard collection classes for + * detecting cyclic dependences and avoiding recursion. + * + */ + private static final class ObjectElem { + private Object _object; + + public ObjectElem(Object aObject) { + _object = aObject; + } + + public boolean equals(Object aObj) { + return ((ObjectElem) aObj)._object == _object; + } + + public int hashCode() { + return _object.hashCode(); + } + } + + /** + * Constructs the object. + * + */ + public HibernateSupport() { + // Empty + } + + /** + * Performes a hibernate 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. + */ + public static void merge(HibernateTemplate aTemplate, Persistent aPersistent) { + Persistent merged = (Persistent) aTemplate.merge(aPersistent); + processPersistent(aPersistent, merged, new ArrayList()); + } + + /** + * Copies primary keys and version from the result of the merged to the + * object that was passed to the merge operation. It does this by traversing + * the properties of the object. It copies the primary key and version for + * objects that implement {@link Persistent} and applies the same rules to + * objects in maps and sets as well (i.e. recursively). + * + * @param aPersistent + * Object whose primary key and version are to be set. + * @param aMerged + * Object that was the result of the merge. + * @param aProcessed + * List of already processed Persistent objects of the persistent + * part. + */ + public static void processPersistent(Persistent aPersistent, + Persistent aMerged, List aProcessed) { + if (aPersistent == null && aMerged == null) { + return; + } + if (aPersistent == null || aMerged == null) { + throw new RuntimeException("persistent or merged object is null '" + + aPersistent + "'" + " '" + aMerged + "'"); + } + ObjectElem elem = new ObjectElem(aPersistent); + if (aProcessed.contains(elem)) { + return; // already processed. + } + aProcessed.add(elem); + + LOG.debug("Setting pk/version on " + aPersistent + " from " + aMerged); + + if (aPersistent.getPrimaryKey() != null + && !aMerged.getPrimaryKey().equals(aPersistent.getPrimaryKey())) { + LOG.error("Mismatch between primary key values: " + aPersistent + + " " + aMerged); + } else { + aPersistent.setPersistedVersion(aMerged.getPersistedVersion()); + aPersistent.setPrimaryKey(aMerged.getPrimaryKey()); + } + + Method[] methods = aPersistent.getClass().getMethods(); + for (Method getter : methods) { + if (getter.getName().startsWith("get")) { + Class returnType = getter.getReturnType(); + + try { + if (Set.class.isAssignableFrom(returnType)) { + Set merged = (Set) getter.invoke(aMerged); + Set persistent = (Set) getter.invoke(aPersistent); + processSet(persistent, merged, aProcessed); + } else if (List.class.isAssignableFrom(returnType)) { + List merged = (List) getter.invoke(aMerged); + List persistent = (List) getter.invoke(aPersistent); + processList(persistent, merged, aProcessed); + } else if (Map.class.isAssignableFrom(returnType)) { + Map merged = (Map) getter.invoke(aMerged); + Map persistent = (Map) getter.invoke(aPersistent); + processMap(persistent, merged, aProcessed); + } else if (Persistent.class.isAssignableFrom(returnType)) { + Persistent merged = (Persistent) getter.invoke(aMerged); + Persistent persistent = (Persistent) getter + .invoke(aPersistent); + processPersistent(persistent, merged, aProcessed); + } else if (returnType.isArray() + && Persistent.class.isAssignableFrom(returnType + .getComponentType())) { + Persistent[] merged = (Persistent[]) getter + .invoke(aMerged); + Persistent[] persistent = (Persistent[]) getter + .invoke(aPersistent); + for (int i = 0; i < persistent.length; i++) { + processPersistent(persistent[i], merged[i], + aProcessed); + } + } + } catch (InvocationTargetException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e.getMessage(), e); + } + } + } + + } + + /** + * Process the persistent objects in the collections. + * + * @param aPersistent + * Collection in the original object. + * @param aMerged + * Collection as a result of the merge. + * @param aProcessed + * List of processed persistent objects. + */ + public static void processList(List aPersistent, List aMerged, + List aProcessed) { + Object[] merged = aMerged.toArray(); + Object[] persistent = aPersistent.toArray(); + if (merged.length != persistent.length) { + throw new RuntimeException("Array sizes differ " + merged.length + + " " + persistent.length); + } + for (int i = 0; i < merged.length; i++) { + assert merged[i].equals(persistent[i]); + if (merged[i] instanceof Persistent) { + processPersistent((Persistent) persistent[i], + (Persistent) merged[i], aProcessed); + } + } + } + + /** + * Process the persistent objects in sets. + * + * @param aPersistent + * Collection in the original object. + * @param aMerged + * Collection as a result of the merge. + * @param aProcessed + * List of processed persistent objects. + */ + public static void processSet(Set aPersistent, Set aMerged, + List aProcessed) { + if (aMerged.size() != aPersistent.size()) { + throw new RuntimeException("Array sizes differ " + aMerged.size() + + " " + aPersistent.size()); + } + for (Object merged : aMerged) { + // Find the object that equals the merged[i] + for (Object persistent : aPersistent) { + if (persistent.equals(merged)) { + processPersistent((Persistent) persistent, + (Persistent) merged, aProcessed); + break; + } + } + } + } + + /** + * Process the Map objects in the collections. + * + * @param aPersistent + * Collection in the original object. + * @param aMerged + * Collection as a result of the merge. + * @param aProcessed + * List of processed persistent objects. + */ + public static void processMap(Map aPersistent, Map aMerged, + List aProcessed) { + if (aMerged.size() != aPersistent.size()) { + throw new RuntimeException("Sizes differ " + aMerged.size() + " " + + aPersistent.size()); + } + Set keys = aMerged.keySet(); + for (Object key : keys) { + if (!aPersistent.containsKey(key)) { + throw new RuntimeException("Key '" + key + "' not found"); + } + Object mergedValue = aMerged.get(key); + Object persistentValue = aPersistent.get(key); + if (mergedValue instanceof Persistent) { + if (persistentValue instanceof Persistent) { + processPersistent((Persistent) persistentValue, + (Persistent) mergedValue, aProcessed); + } else { + throw new RuntimeException( + "Value in original object is null, whereas merged object contains a value"); + } + } + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/package.html b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/package.html new file mode 100644 index 00000000..6f14b9f2 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/main/java/org/wamblee/persistence/hibernate/package.html @@ -0,0 +1,15 @@ + + + + wamblee.org + + + +This package provides support utilities for persistence with hibernate. + + + +@since - + + + diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java new file mode 100644 index 00000000..b56beacd --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/concurrency/spring/LockAdviceTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.concurrency.spring; + +import org.springframework.aop.framework.ProxyFactoryBean; +import org.wamblee.concurrency.AbstractLockTestCase; +import org.wamblee.concurrency.JvmLock; +import org.wamblee.concurrency.spring.LockAdvice; +import org.wamblee.test.TimingUtils; + +/** + * + * + * @author Erik Brakkee + */ +public class LockAdviceTest extends AbstractLockTestCase { + + private class Runner implements Runnable { + public void run() { + LockAdviceTest.this.getTracker().eventOccurred(ACQUIRED); + TimingUtils.sleep(SLEEP_TIME); + } + } + + private Runnable _target; + + /* + * (non-Javadoc) + * + * @see org.wamblee.concurrency.AbstractLockTestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + + Runner runner = new Runner(); + LockAdvice advice = new LockAdvice(new JvmLock()); + + ProxyFactoryBean support = new ProxyFactoryBean(); + support.setInterfaces(new Class[]{ Runnable.class }); + support.setTarget(runner); + support.addAdvice(advice); + _target = (Runnable)support.getObject(); + + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.concurrency.AbstractLockTestCase#runThread() + */ + @Override + protected Thread runThread() { + Thread t = new Thread(new Runnable() { + public void run() { + try { + getTracker().eventOccurred(STARTED); + _target.run(); + getTracker().eventOccurred(RELEASED); + } catch (Throwable e) { + throw new RuntimeException(e); + } + }; + }); + t.start(); + return t; + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java new file mode 100644 index 00000000..21bf1957 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/general/spring/SpringBeanFactoryTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.general.spring; + +import org.wamblee.general.BeanFactoryException; + +import junit.framework.TestCase; + +/** + * Tests the spring bean factory. + * + * @author Erik Brakkee + */ +public class SpringBeanFactoryTest extends TestCase { + + /* + * (non-Javadoc) + * + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + + } + + public void testExistingBeanRefContext() { + SpringBeanFactory factory = new SpringBeanFactory( + "org/wamblee/general/beanRefContext.xml", "test"); + + String value1 = factory.find(String.class); + assertEquals("hello", value1); + String value2 = (String) factory.find("java.lang.String"); + assertEquals("hello", value2); + String value3 = factory.find("java.lang.String", String.class); + assertEquals("hello", value3); + + try { + factory.find("unknown"); + } catch (BeanFactoryException e) { + return; // ok + } + fail(); + } + + public void testUnknownBeanFactory() { + try { + new SpringBeanFactory( + "org/wamblee/general/beanRefContext.xml", "unknown"); + } catch (BeanFactoryException e) { + return; // ok + } + fail(); + } +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java new file mode 100644 index 00000000..e5e566ce --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/general/spring/TestBeanFactory.java @@ -0,0 +1,30 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.general.spring; + +/** + * Test bean factory. + * + * @author Erik Brakkee + */ +public class TestBeanFactory extends SpringBeanFactory { + + + public TestBeanFactory() { + super("org/wamblee/general/beanRefContext.xml", "test"); + } +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java new file mode 100644 index 00000000..aefe4185 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateExporter.java @@ -0,0 +1,52 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.test.spring; + +import java.io.File; +import java.io.IOException; + +import org.hibernate.cfg.Configuration; +import org.hibernate.tool.hbm2ddl.SchemaExport; + +/** + * Exporting the hibernate mapping. + * + * @author Erik Brakkee + */ +public final class HibernateExporter { + + /** + * Disabled constructor. + * + */ + private HibernateExporter() { + // Empty + } + + public static void main(String[] aArgs) throws IOException { + String file = aArgs[0]; + File dir = new File(aArgs[1]); + + Configuration conf = HibernateUtils.getConfiguration(dir); + + SchemaExport export = new SchemaExport(conf); + export.setDelimiter(";"); + export.setOutputFile(file); + export.create(true, false); + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java new file mode 100644 index 00000000..87219de0 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateUpdater.java @@ -0,0 +1,50 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.test.spring; + +import java.io.File; +import java.io.IOException; + +import org.hibernate.cfg.Configuration; +import org.hibernate.tool.hbm2ddl.SchemaUpdate; + +/** + * Exporting the hibernate mapping. + * + * @author Erik Brakkee + */ +public final class HibernateUpdater { + + /** + * Disabled constructor. + * + */ + private HibernateUpdater() { + // Empty + } + + public static void main(String[] aArgs) throws IOException { + String file = aArgs[0]; + File dir = new File(file); + + Configuration conf = HibernateUtils.getConfiguration(dir); + + SchemaUpdate lSchemaUpdate = new SchemaUpdate(conf); + lSchemaUpdate.execute(true, true); + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java new file mode 100644 index 00000000..74a7ef7e --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/HibernateUtils.java @@ -0,0 +1,93 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.test.spring; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + +import org.apache.oro.io.AwkFilenameFilter; +import org.hibernate.cfg.Configuration; +import org.wamblee.io.ClassPathResource; +import org.wamblee.io.InputResource; + +/** + * Hibernate utilities. + * + * @author Erik Brakkee + */ +public final class HibernateUtils { + + private static final String DATABASE_PROPS = "test.database.properties"; + + /** + * Disabled. + * + */ + private HibernateUtils() { + // Empty + } + + /** + * @param aDir + * @return + */ + public static Configuration getConfiguration(File aDir) throws IOException { + Configuration conf = new Configuration(); + File[] files = aDir.listFiles((FileFilter) (new AwkFilenameFilter( + ".*\\.hbm\\.xml"))); + for (File f : files) { + System.out.println("Mapping file: " + f); + conf.addFile(f); + } + + Map dbProps = getHibernateProperties(); + + for (Map.Entry entry : dbProps.entrySet()) { + System.out.println("Property: " + entry.getKey() + "=" + + entry.getValue()); + conf.setProperty(entry.getKey(), entry.getValue()); + } + + return conf; + } + + private static Map getHibernateProperties() + throws IOException { + + System.out.println("Reading properties file: " + DATABASE_PROPS); + InputResource lPropFile = new ClassPathResource(DATABASE_PROPS); + Properties props = new Properties(); + props.load(lPropFile.getInputStream()); + + Map 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")); + + return result; + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java new file mode 100644 index 00000000..a7cc6fe6 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestSpringBeanFactory.java @@ -0,0 +1,63 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.test.spring; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.wamblee.general.BeanFactory; +import org.wamblee.general.BeanFactoryException; + +/** + * Bean factory which uses Spring. + * + * @author Erik Brakkee + */ +public class TestSpringBeanFactory implements BeanFactory { + + private ApplicationContext _context; + + public TestSpringBeanFactory(ApplicationContext aContext) { + _context = aContext; + } + + /* (non-Javadoc) + * @see org.wamblee.general.BeanFactory#find(java.lang.String) + */ + public Object find(String aId) { + return find(aId, Object.class); + } + + /* (non-Javadoc) + * @see org.wamblee.general.BeanFactory#find(java.lang.Class) + */ + public T find(Class aClass) { + return find(aClass.getName(), aClass); + } + + /* (non-Javadoc) + * @see org.wamblee.general.BeanFactory#find(java.lang.String, java.lang.Class) + */ + public T find(String aId, Class aClass) { + try { + Object obj = _context.getBean(aId, aClass); + assert obj != null; + return aClass.cast(obj); + } catch (BeansException e) { + throw new BeanFactoryException(e.getMessage(), e); + } + } + +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java new file mode 100644 index 00000000..37ea898b --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallback.java @@ -0,0 +1,35 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.test.spring; + +import java.util.Map; + +/** + * Transaction callback for testing. The test will fail if any type of exception + * is thrown. + * + * @author Erik Brakkee + */ +public interface TestTransactionCallback { + /** + * Executes code within a transaction, causing the testcase to fail if any + * type of exception is thrown. + * + * @return A map containg the resuls of the execution. This is a convenient + * method of returning multiple results from a call. + */ + Map execute() throws Exception; +} diff --git a/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java new file mode 100644 index 00000000..a5011e48 --- /dev/null +++ b/tags/wamblee-utils-0.2/support/spring/src/test/java/org/wamblee/test/spring/TestTransactionCallbackWithoutResult.java @@ -0,0 +1,31 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.test.spring; + +/** + * Transaction callback for testing. The test will fail if any type of exception + * is thrown. + * + * @author Erik Brakkee + */ +public interface TestTransactionCallbackWithoutResult { + /** + * Executes code within a transaction, causing the testcase to fail if any + * type of exception is thrown. + * + */ + void execute() throws Exception; +} diff --git a/tags/wamblee-utils-0.2/system/TODO.txt b/tags/wamblee-utils-0.2/system/TODO.txt new file mode 100644 index 00000000..cac157b2 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/TODO.txt @@ -0,0 +1,78 @@ +SetterConfiguration: +- add type based removal of setters. +- add values(Class aType) method for selecting a setter. +- add add(Class aType) method for selecting a type. +- verify that superclass setters are also taken into account. + + + +opzoeken waar de provided interfaces van de scope gebruikt worden, als het +goed is nog nergens. Scope moet een Component worden en publiceren van een +interface leidt tot een nieuw provided interface. + +Component infrastructure +* support simple component + - requires through constructor + - provides through getters +* optional start and stop methods +* giving names to a component must be optional +* support for cached components and non-cached components. + + +- Annotaties definieren + + +@Component + class MyComponent { + + public MyComponent(Def aArg, Ghi aArg2) { + } + + @Provided(name = "name") + public Xyz getXyz(); + + @Start + public void myStart(); // Unlike the component +} + +- Algemene classes maken die de constructor, start method, en + methodes identificeren om de component als Component te benaderen. + in een object, samen met een wrapper die deze info gebruikt om het + object als Component te exportern. + Er moet ook een wrapper zijn voor reeds geinstantieerde objecten. + +- wrapper maken die geannoteerde classes interpreteert en via de eerdere + wrapper het object ontsluiten als component. + Zowel geinstantieerde objecten als classes ondersteunen. + +- add support for private setters. +- add support or exposing provided services + - superclass or interface of the concrete type instead of the concrete type + or not based on the concrete type at all. + - based on getters. +- add support for field injection. + +- add support for annotation based configuration instead of API-based + +- add support for type conversions. + +- add support for multiplicity. + +- add support for aggregating multiple servicss. + +- add support for explicitly configuring which provided interface of + a container is provided by which internal service. + +- do not use equality but use logic for matching external required and + provided interfaces of a container. + + e.g. a service T provided by a container can be provided by a service + U that provides subclasses of the provided interfaces of T + + a service T required by a component inside a container is covered + by stronger requirements for subclasses of T. + +- separate logic for connecting required and provided interfaces + through a general graph model of the application. + Then use generic filters, validations, and graph traversal APIs + to implement the current functionality in the container. diff --git a/tags/wamblee-utils-0.2/system/general/pom.xml b/tags/wamblee-utils-0.2/system/general/pom.xml new file mode 100644 index 00000000..c62329ac --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/pom.xml @@ -0,0 +1,40 @@ + + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-system-general + jar + /system/general + http://wamblee.org + + + commons-logging + commons-logging + + + org.wamblee + wamblee-support-general + 0.2 + + + org.wamblee + wamblee-support-general + test-jar + 0.2 + + + org.wamblee + wamblee-test-enterprise + 0.2 + test + + + + diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java new file mode 100644 index 00000000..ace1525d --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ClassAdapter.java @@ -0,0 +1,56 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +/** + * A Class Adapter adapts a given class to a Component. + * + * @author Erik Brakkee + */ +public class ClassAdapter extends AbstractComponent { + + private ClassConfiguration _classConfig; + + public ClassAdapter(String aName, ClassConfiguration aClassConfig) { + super(aName, + aClassConfig.getProvidedInterfaces().toArray(new ProvidedInterface[0]), + aClassConfig.getRequiredInterfaces().toArray(new RequiredInterface[0])); + _classConfig = aClassConfig; + } + + @Override + protected Object doStart(Scope aScope) { + + Object obj = _classConfig.create(aScope); + _classConfig.inject(aScope, obj); + + for (ProvidedInterface provided: getProvidedInterfaces()) { + addInterface(provided, obj, aScope); + } + + return obj; + } + + @Override + protected void doStop(Object aRuntime) { + // Empty. + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java new file mode 100644 index 00000000..0fee7aca --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ClassConfiguration.java @@ -0,0 +1,88 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +/** + * The class configuration encapsulates the knowledge of how to wrap a class as a component. + * + * @author Erik Brakkee + * + */ +public class ClassConfiguration { + + private Class _class; + private ConstructorConfiguration _constructorConfig; + private ObjectConfiguration _objectConfig; + + /** + * Constructs the configuration. By default no constructor is selected and + * one of {@link #select(Class...)} or + * {@link #greedy()} must be called. + * @param aClass Class to construct. + */ + public ClassConfiguration(Class aClass) { + _class = aClass; + _constructorConfig = new ConstructorConfiguration(aClass); + _objectConfig = new ObjectConfiguration(aClass); + } + + public ConstructorConfiguration getConstructorConfig() { + return _constructorConfig; + } + + public ObjectConfiguration getObjectConfig() { + return _objectConfig; + } + + /** + * Creates the object in the given scope. + * @param aScope Scope containing required interfaces for this object. + * @return object. + */ + public Object create(Scope aScope) { + return _constructorConfig.create(aScope); + } + + /** + * Injects required interfaces through the setters + * @param aObject Object to inject into. + * @param aScope Scope in which injection takes place. + */ + public void inject(Scope aScope, Object aObject) { + _objectConfig.inject(aScope, aObject); + } + + public List 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; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java new file mode 100644 index 00000000..7a5c259d --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ConstructorConfiguration.java @@ -0,0 +1,179 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.wamblee.collections.CollectionFilter; +import org.wamblee.conditions.Condition; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.core.SystemAssemblyException; + +/** + * Class that allows configuration of the constructor to use. + * + * In particular, it provides: + *
    + *
  • 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 _class; + private Constructor _constructor; + private ParameterValues _values; + private boolean _publicOnly; + + /** + * Constructs the configuration. By default the public constructor with the + * most arguments will be used. + * @param aClass Class to construct. + */ + public ConstructorConfiguration(Class aClass) { + _class = aClass; + _constructor = null; + _publicOnly = true; + } + + /** + * Sets whether or no non public constructors are also considered. + * Reset the choice of a constructor to its default. + * @param aNonPublic + * @return + */ + public ConstructorConfiguration setNonPublic(boolean aNonPublic) { + _publicOnly = !aNonPublic; + _constructor = null; + _values = null; + return this; + } + + /** + * Selects an explicit constructor. + * @param aTypes Arguments of the constructor. + * @return Return the injector to allow call chaining. + */ + public ConstructorConfiguration select(Class... aTypes) { + try { + _constructor = _class.getDeclaredConstructor(aTypes); + } catch (Exception e) { + throw new SystemAssemblyException(e.getMessage(), e); + } + resetValues(); + return this; + } + + /** + * Selects the greediest constructor. + * @return The injector to allow call chaining. + * @throws SystemAssemblyException if the greediest constructor cannot be uniquely + * identified. + */ + public ConstructorConfiguration greedy() { + Constructor[] declared = _class.getDeclaredConstructors(); + if (declared.length == 0) { + throw new SystemAssemblyException("Class '" + _class + + " is an interface, primitive type, or array"); + } + int max = -1; + List> 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[] values = _values.values(aScope); + try { + return getConstructor().newInstance(values); + } catch (Exception e) { + throw new SystemAssemblyException("Could not construct object " + + getConstructor() + " " + Arrays.asList(values), e); + } + } + + public List getRequiredInterfaces() { + getConstructor(); // initialize constructor if needed. + return _values.getRequiredInterfaces(); + } + + private Constructor getConstructor() { + if (_constructor == null ) { + greedy(); + } + return _constructor; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java new file mode 100644 index 00000000..823b7c0d --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/DefaultContainer.java @@ -0,0 +1,60 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.container.Container; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; + +public class DefaultContainer extends Container { + + public DefaultContainer(String aName) { + super(aName); + } + + @Override + public DefaultContainer addComponent(Component aComponent) { + super.addComponent(aComponent); + return this; + } + + public DefaultContainer addComponent(String aName, ClassConfiguration aConfiguration) { + return addComponent(new ClassAdapter(aName, aConfiguration)); + } + + public DefaultContainer addComponent(String aName, Object aObject, ObjectConfiguration aConfiguration) { + if ( !aConfiguration.appliesTo(aObject) ) { + throw new IllegalArgumentException("Configuration '" + aConfiguration + "' does nto applu to '" + + aObject + "'"); + } + return addComponent(new ObjectAdapter(aName, aObject, aConfiguration)); + } + + + @Override + public DefaultContainer addRequiredInterface(RequiredInterface aRequired) { + super.addRequiredInterface(aRequired); + return this; + } + + @Override + public DefaultContainer addProvidedInterface(ProvidedInterface aProvided) { + super.addProvidedInterface(aProvided); + return this; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java new file mode 100644 index 00000000..98fa48af --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/FixedValueProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.Scope; + +/** + * Value provider that provides a fixed value. + * + * @author Erik Brakkee + */ +class FixedValueProvider implements ValueProvider { + + private Object _value; + + /** + * Constructs the value. + * @param aValue Value to construct. + */ + public FixedValueProvider(Object aValue) { + _value = aValue; + } + + @Override + public Object getValue(Scope aScope) { + return _value; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java new file mode 100644 index 00000000..ff2fa0a2 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ObjectAdapter.java @@ -0,0 +1,58 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +/** + * An adapter class that adapts an existing object to a component. + * + * @author Erik Brakkee + */ +public class ObjectAdapter extends AbstractComponent { + + private ObjectConfiguration _objectConfig; + private Object _object; + + public ObjectAdapter(String aName, Object aObject, ObjectConfiguration aObjectConfig) { + super(aName, + new ProvidedInterface[] { new DefaultProvidedInterface(aName, aObject.getClass()) }, + aObjectConfig.getRequiredInterfaces().toArray(new RequiredInterface[0])); + _objectConfig = aObjectConfig; + _object = aObject; + } + + @Override + protected Object doStart(Scope aScope) { + + _objectConfig.inject(aScope, _object); + + for (ProvidedInterface provided: getProvidedInterfaces()) { + addInterface(provided, _object, aScope); + } + + return _object; + } + + @Override + protected void doStop(Object aRuntime) { + // Empty. + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java new file mode 100644 index 00000000..22df0491 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ObjectConfiguration.java @@ -0,0 +1,62 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +/** + * General configuration for an instantiated object. + * + * @author Erik Brakkee + */ +public class ObjectConfiguration { + + private Class _class; + private SetterConfiguration _setterConfig; + + public ObjectConfiguration(Class aClass) { + _class = aClass; + _setterConfig = new SetterConfiguration(aClass); + } + + /** + * Performs injection into an object of the configured class + * using information from the given scope. + * @param aScope Scope. + * @param aObject Object. + */ + public void inject(Scope aScope, Object aObject) { + _setterConfig.inject(aScope, aObject); + } + + public SetterConfiguration getSetterConfig() { + return _setterConfig; + } + + public List getRequiredInterfaces() { + List result = new ArrayList(); + result.addAll(_setterConfig.getRequiredInterfaces()); + return result; + } + + public boolean appliesTo(Object aObject) { + return _class.isInstance(aObject); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java new file mode 100644 index 00000000..17789818 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ParameterValues.java @@ -0,0 +1,132 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +/** + * Represents parameter values for a method or constructor and allows for the configuration + * of how these values are retrieved. + * + * @author Erik Brakkee + */ +public class ParameterValues { + private String[] _names; + private Class[] _types; + private ValueProvider[] _values; + + /** + * Constructs the configuration. By default no constructor is selected and + * one of {@link #select(Class...)} or + * {@link #greedy()} must be called. + * @param aClass Class to construct. + */ + public ParameterValues(Class[] aTypes) { + _names = new String[aTypes.length]; + for (int i = 0; i < aTypes.length; i++) { + _names[i] = "arg" + i; + } + _types = aTypes; + resetValues(); + } + + /** + * Constructs the configuration. By default no constructor is selected and + * one of {@link #select(Class...)} or + * {@link #greedy()} must be called. + * @param aNames Names of the arguments. + * @param aClass Class to construct. + */ + public ParameterValues(String[] aNames, Class[] aTypes) { + assert aNames.length == aTypes.length; + _names = aNames; + _types = aTypes; + resetValues(); + } + + /** + * The types of the parameter values. + * @return Types. + */ + public Class[] getTypes() { + return _types; + } + + /** + * Sets argument i to be optional, meaning that null is allowed to be passed in. + * @param aArg Argument to set. + */ + public ParameterValues setOptional(int aArg) { + _values[aArg] = new RequiredInterfaceProvider(new DefaultRequiredInterface( + "arg" + aArg, _types[aArg], true)); + return this; + } + + /** + * Sets the argument i to a fixed value. + * @param aArg Argument to set. + * @param aValue Value. + */ + public ParameterValues setValue(int aArg, Object aValue) { + _values[aArg] = new FixedValueProvider(aValue); + return this; + } + + /** + * Resets the values. + */ + private void resetValues() { + _values = new ValueProvider[_types.length]; + for (int i = 0; i < _values.length; i++) { + _values[i] = new RequiredInterfaceProvider(new DefaultRequiredInterface( + _names[i], _types[i])); + } + } + + /** + * Gets the required interfaces to provide values that are not provided + * in another way. + * @return Required interfaces. + */ + public List 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[] values = new Object[_values.length]; + for (int i = 0; i < _values.length; i++) { + values[i] = _values[i].getValue(aScope); + } + return values; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java new file mode 100644 index 00000000..56170aed --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/RequiredInterfaceProvider.java @@ -0,0 +1,47 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +/** + * Value provider that provides a value through a required interface. + * + * @author Erik Brakkee + */ +class RequiredInterfaceProvider implements ValueProvider { + + private RequiredInterface _required; + + /** + * Constructs the provider + * @param aRequired Required interface. + */ + public RequiredInterfaceProvider(RequiredInterface aRequired) { + _required = aRequired; + } + + @Override + public Object getValue(Scope aScope) { + return aScope.getInterfaceImplementation(_required.getProvider(), Object.class); + } + + public RequiredInterface getRequiredInterface() { + return _required; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java new file mode 100644 index 00000000..57323a54 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/SetterConfiguration.java @@ -0,0 +1,303 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.awt.CompositeContext; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.wamblee.collections.CollectionFilter; +import org.wamblee.conditions.Condition; +import org.wamblee.conditions.FixedCondition; +import org.wamblee.general.Pair; +import org.wamblee.reflection.ReflectionUtils; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.core.SystemAssemblyException; + +/** + * Represents the configuration for exposing the setters of a class as required + * interfaces. + * + * @author Erik Brakkee + */ +public class SetterConfiguration { + + private Class _class; + private boolean _publicOnly; + + private Map _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)) { + _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()); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java new file mode 100644 index 00000000..6582f8fc --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/adapters/ValueProvider.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.Scope; + +/** + * Interface used to provide values for arguments of methods and constructors. + * + * @author Erik Brakkee + */ +interface ValueProvider { + + Object getValue(Scope aScope); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/components/ORMappingConfig.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/components/ORMappingConfig.java new file mode 100644 index 00000000..880e869e --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/components/ORMappingConfig.java @@ -0,0 +1,61 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.components; + +public class ORMappingConfig { + + public enum DatabaseType { + MYSQL_INNO_DB, DERBY; + + public static interface Switch { + T handleMySqlInnoDb(); + + T handleDerby(); + } + + public T handleCases(Switch aSwitch) { + + switch (this) { + case MYSQL_INNO_DB: { + return aSwitch.handleMySqlInnoDb(); + } + case DERBY: { + return aSwitch.handleDerby(); + } + default: { + throw new RuntimeException("Unhandled case " + this); + } + } + } + }; + + private boolean _schemaUpdate; + private DatabaseType _type; + + public ORMappingConfig(boolean aSchemaUpdate, DatabaseType aType) { + _schemaUpdate = aSchemaUpdate; + _type = aType; + } + + public boolean isSchemaUpdate() { + return _schemaUpdate; + } + + public DatabaseType getType() { + return _type; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java new file mode 100644 index 00000000..d3c7e070 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/components/PropertyComponent.java @@ -0,0 +1,70 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.components; + +import java.io.IOException; +import java.util.Properties; + +import org.wamblee.io.InputResource; +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.Scope; + +/** + * Property component that reads a property file and provides + * it to other components through a provided interface. + * + * NOTE: when multiple property components are used, disambiguation + * of provided and required interfaces is needed. + * + * @author Erik Brakkee + */ +public class PropertyComponent extends AbstractComponent { + + private static ProvidedInterface PROPS = new DefaultProvidedInterface("props", Properties.class); + + private Properties _props; + + public PropertyComponent(String aName, InputResource aResource) throws IOException { + this(aName, readProps(aResource)); + } + + private static Properties readProps(InputResource aResource) throws IOException { + Properties props = new Properties(); + props.load(aResource.getInputStream()); + return props; + } + + public PropertyComponent(String aName, Properties aProps) { + super(aName); + _props = aProps; + + addProvidedInterface(PROPS); + } + + @Override + protected Properties doStart(Scope aScope) { + addInterface(PROPS, _props, aScope); + return _props; + } + + @Override + protected void doStop(Properties aRuntime) { + // Empty + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/container/Container.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/container/Container.java new file mode 100644 index 00000000..9669cb21 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/container/Container.java @@ -0,0 +1,387 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.container; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wamblee.general.Pair; +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultScope; +import org.wamblee.system.core.NamedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.system.graph.CompositeEdgeFilter; +import org.wamblee.system.graph.component.ComponentGraph; +import org.wamblee.system.graph.component.ConnectExternalProvidedProvidedFilter; +import org.wamblee.system.graph.component.ConnectRequiredExternallyRequiredEdgeFilter; +import org.wamblee.system.graph.component.ConnectRequiredProvidedEdgeFilter; + +/** + * Container consisting of multiple components. + * + * @author Erik Brakkee + */ +public class Container extends AbstractComponent { + + private static final Log LOG = LogFactory.getLog(Container.class); + + private List _components; + private CompositeEdgeFilter _edgeFilter; + private boolean _sealed; + + /** + * Constructs the container + * + * @param aName + * Name of the container + * @param aComponents + * Components. + * @param aProvided + * Provided services of the container + * @param aRequired + * Required services by the container. + */ + public Container(String aName, Component[] aComponents, + List aProvided, List aRequired) { + super(aName, aProvided, aRequired); + _components = new ArrayList(); + + _edgeFilter = new CompositeEdgeFilter(); + _sealed = false; + for (Component component : aComponents) { + addComponent(component); + } + } + + /** + * Constructs the container + * + * @param aName + * Name of the container + * @param aComponents + * Components. + * @param aProvided + * Provided services of the container + * @param aRequired + * Required services by the container. + */ + public Container(String aName, Component[] aComponents, + ProvidedInterface[] aProvided, RequiredInterface[] aRequired) { + this(aName, aComponents, Arrays.asList(aProvided), Arrays.asList(aRequired)); + } + + public Container(String aName) { + this(aName, new Component[0], new ProvidedInterface[0], + new RequiredInterface[0]); + } + + public Container addComponent(Component aComponent) { + checkSealed(); + if (aComponent.getContext() != null) { + throw new SystemAssemblyException( + "Inconsistent hierarchy, component '" + + aComponent.getName() + + "' is already part of another hierarchy"); + } + if ( findComponent(aComponent.getName()) != null ) { + throw new SystemAssemblyException("Duplicate component '" + + aComponent.getName() + "'"); + } + _components.add(aComponent); + aComponent.addContext(getQualifiedName()); + return this; + } + + /** + * Explictly connects required and provided interfaces. + * @param aClientComponent Client component, may not be null. + * @param aRequiredInterface Required interface. If null it means all required interfaces. + * @param aServerComponent Server component to connect to. If null, it means that no server components + * may be connected to and the provider of the required interface will be null. + * @param aProvidedInterface Provided interface. If null, it means that there is no restriction on the + * name of the provided interface and that it is automatically selected. + */ + public void connectRequiredProvided(String aClientComponent, String aRequiredInterface, + String aServerComponent, String aProvidedInterface) { + checkSealed(); + Component client = findComponent(aClientComponent); + Component server = findComponent(aServerComponent); + if ( client == null ) { + throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aClientComponent + "' in the container"); + } + if ( aRequiredInterface != null ) { + if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) { + throw new SystemAssemblyException( + getQualifiedName() + ": Component '" + aClientComponent + "' does not have a required interface named '" + + aRequiredInterface + "'"); + } + } + if ( server == null ) { + throw new SystemAssemblyException("No component '" + aClientComponent + "' in the container"); + } + if ( aProvidedInterface != null ) { + if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) { + throw new SystemAssemblyException( + getQualifiedName() + ": Component '" + aServerComponent + "' does not have a provided interface named '" + + aProvidedInterface + "'"); + } + } + _edgeFilter.add(new ConnectRequiredProvidedEdgeFilter(aClientComponent, aRequiredInterface, aServerComponent, aProvidedInterface)); + } + + /** + * Explicitly connects a externally required interface to an internally required interface. + * @param aComponent Component requiring the interface (must be non-null). + * @param aRequiredInterface Required interface of the component (must be non-null). + * @param aExternalRequiredInterface Externally required interface (must be non-null). + */ + public void connectExternalRequired(String aComponent, String aRequiredInterface, + String aExternalRequiredInterface) { + checkSealed(); + Component client = findComponent(aComponent); + if ( client == null ) { + throw new SystemAssemblyException(getQualifiedName() + ": No component '" + aComponent + "' in the container"); + } + if ( aRequiredInterface != null ) { + if ( findInterface(client.getRequiredInterfaces(), aRequiredInterface) == null ) { + throw new SystemAssemblyException( + getQualifiedName() + ": Component '" + aComponent + "' does not have a required interface named '" + + aRequiredInterface + "'"); + } + } + if ( aExternalRequiredInterface != null) { + if ( findInterface(getRequiredInterfaces(), aExternalRequiredInterface) == null ) { + throw new SystemAssemblyException( + getQualifiedName() + ": container does not have a required interface named '" + + aExternalRequiredInterface + "'"); + } + } + _edgeFilter.add(new ConnectRequiredExternallyRequiredEdgeFilter( + aComponent, aRequiredInterface, aExternalRequiredInterface)); + } + + public void connectExternalProvided(String aExternalProvided, String aComponent, String aProvidedInterface) { + checkSealed(); + Component server = findComponent(aComponent); + + + if ( server == null ) { + throw new SystemAssemblyException("No component '" + aComponent + "' in the container"); + } + if ( aProvidedInterface != null ) { + if ( findInterface(server.getProvidedInterfaces(), aProvidedInterface) == null) { + throw new SystemAssemblyException( + getQualifiedName() + ": Component '" + aComponent + "' does not have a provided interface named '" + + aProvidedInterface + "'"); + } + } + if ( aExternalProvided != null ) { + if ( findInterface(getProvidedInterfaces(), aExternalProvided) == null) { + throw new SystemAssemblyException( + getQualifiedName() + ": Container does not have a provided interface named '" + + aExternalProvided + "'"); + } + } + _edgeFilter.add(new ConnectExternalProvidedProvidedFilter(aExternalProvided, aComponent, aProvidedInterface)); + } + + + @Override + public Container addProvidedInterface(ProvidedInterface aProvided) { + checkSealed(); + super.addProvidedInterface(aProvided); + return this; + } + + @Override + public Container addRequiredInterface(RequiredInterface aRequired) { + checkSealed(); + super.addRequiredInterface(aRequired); + return this; + } + + @Override + public void addContext(String aContext) { + super.addContext(aContext); + for (Component component : _components) { + component.addContext(aContext); + } + } + + /** + * Validates the components together to check that there are no required + * services not in the required list and no services in the provided list + * that cannot be provided. Also logs a warning in case of superfluous + * requirements. + * + * @throws SystemAssemblyException + * in case of any validation problems. + */ + public void validate() { + doStartOptionalDryRun(null, true); + } + + /** + * Seal the container, meaning that no further components or interfaces may + * be added. + */ + public void seal() { + _sealed = true; + } + + /** + * Checks if the container is sealed. + * + * @return True iff the container is sealed. + */ + public boolean isSealed() { + return _sealed; + } + + /** + * Utility method to start with an empty external scope. This is useful for + * top-level containers which are not part of another container. + * + * @return Scope. + */ + public Scope start() { + Scope scope = new DefaultScope(getProvidedInterfaces()); + return super.start(scope); + } + + @Override + protected Scope doStart(Scope aExternalScope) { + validate(); + Scope scope = new DefaultScope(getProvidedInterfaces().toArray(new ProvidedInterface[0]), aExternalScope); + ComponentGraph graph = doStartOptionalDryRun(scope, false); + exposeProvidedInterfaces(graph, aExternalScope, scope); + seal(); + return scope; + } + + private void exposeProvidedInterfaces(ComponentGraph aGraph, Scope aExternalScope, + Scope aInternalScope) { + for (Pair mapping: + aGraph.findExternalProvidedInterfaceMapping()) { + Object svc = aInternalScope.getInterfaceImplementation(mapping.getSecond(), Object.class); + addInterface(mapping.getFirst(), svc, aExternalScope); + } + } + + private ComponentGraph doStartOptionalDryRun(Scope aScope, boolean aDryRun) { + ComponentGraph graph = createComponentGraph(); + graph.validate(); + graph.link(); + + LOG.info("Starting '" + getQualifiedName() + "'"); + + List started = new ArrayList(); + for (Component component : _components) { + try { + // Start the service. + if (!aDryRun) { + Object runtime = component.start(aScope); + aScope.addRuntime(component, runtime); + started.add(component); + } + } catch (SystemAssemblyException e) { + throw e; + } catch (RuntimeException e) { + LOG.error(getQualifiedName() + ": could not start '" + + component.getQualifiedName() + "'", e); + stopAlreadyStartedComponents(started, aScope); + throw e; + } + } + return graph; + } + + private ComponentGraph createComponentGraph() { + ComponentGraph graph = new ComponentGraph(); + for (RequiredInterface req : getRequiredInterfaces()) { + graph.addRequiredInterface(this, req); + } + for (Component comp : _components) { + graph.addComponent(comp); + } + for (ProvidedInterface prov: getProvidedInterfaces()) { + graph.addProvidedInterface(this, prov); + } + + graph.addEdgeFilter(_edgeFilter); + return graph; + } + + private void stopAlreadyStartedComponents(List aStarted, + Scope aScope) { + // an exception occurred, stop the successfully started + // components + for (int i = aStarted.size() - 1; i >= 0; i--) { + try { + Component component = aStarted.get(i); + aStarted.get(i).stop(aScope.getRuntime(component)); + } catch (Throwable t) { + LOG.error(getQualifiedName() + ": error stopping " + + aStarted.get(i).getQualifiedName()); + } + } + } + + @Override + protected void doStop(Scope aScope) { + for (int i = _components.size() - 1; i >= 0; i--) { + Component component = _components.get(i); + Object runtime = aScope.getRuntime(component); + component.stop(runtime); + } + } + + private void checkSealed() { + if (_sealed) { + throw new SystemAssemblyException("Container is sealed"); + } + } + + /** + * Finds a component based on the non-qualified name of the component. + * @param aName Component name. + * @return Component or null if not found. + */ + public Component findComponent(String aName) { + for (Component component: _components) { + if ( component.getName().equals(aName)) { + return component; + } + } + return null; + } + + private static T findInterface(List aInterfaces, String aInterfaceName) { + for (T intf: aInterfaces) { + if ( intf.getName().equals(aInterfaceName)) { + return intf; + } + } + return null; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java new file mode 100644 index 00000000..d2cf69fe --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/AbstractComponent.java @@ -0,0 +1,213 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Abstract subsystem class making it easy to implement new subsystems. + */ +public abstract class AbstractComponent implements Component { + + 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); + } + + /** + * Constructs the subsystem. + * + * @param aName + * Name of the system. + * @param aProvided + * Provided services. + * @param aRequired + * Required services. + */ + protected AbstractComponent(String aName, ProvidedInterface[] aProvided, + RequiredInterface[] aRequired) { + this(aName, Arrays.asList(aProvided), Arrays.asList(aRequired)); + } + + protected AbstractComponent(String aName) { + this(aName, new ProvidedInterface[0], new RequiredInterface[0]); + } + + public AbstractComponent 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; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/Component.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/Component.java new file mode 100644 index 00000000..9506bb1f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/Component.java @@ -0,0 +1,88 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.List; + +/** + * A component represents a part of a system that requires a + * number of interfaces and provides a number of interfaces. + * + * The component interface provides the meta-data for a component. + * After calling {@link #start(Scope)}, an actual runtime representation of the + * component can be created which is independent of this component. + * As a special case, the runtime representation may be identical to the + * component instance but in general it is not. This allows a component to be + * used as a factory for creating objects. + * + * + * @author Erik Brakkee + */ +public interface Component { + + /** + * Gets the name of the subsystem. + * @return Subsystem name. + */ + String getName(); + + /** + * Prepends the context with a super context. + */ + void addContext(String aContext); + + /** + * Getst the context. + * @return Context or null if not set. + */ + String getContext(); + + /** + * Gets the fully qualified name of the component which includes + * the context of the component. + * This method can only be used after the component has started. + * @return Qualified name. + */ + String getQualifiedName(); + + /** + * Gets a description of the provided interfaces. + * @return Provided interfaces. + */ + List 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); + + /** + * Stops a component. + * @param aRuntime THe runtime part of the component. + */ + void stop(Type aRuntime); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java new file mode 100644 index 00000000..c7905673 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultProvidedInterface.java @@ -0,0 +1,107 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + + +/** + * Default implementation of a service descriptor. + * + * @author Erik Brakkee + */ +public class DefaultProvidedInterface implements ProvidedInterface { + + private String _name; + private Class[] _interfaces; + + /** + * Constructs the descriptor. + * @param aInterface Type of service. + */ + public DefaultProvidedInterface(String aName, Class aInterface) { + this(aName, new Class[] { aInterface }); + } + + public DefaultProvidedInterface(String aName, Class[] aInterfaces) { + _name = aName; + _interfaces = Arrays.copyOf(aInterfaces, aInterfaces.length); + } + + @Override + public String getName() { + return _name; + } + + @Override + public Class[] getInterfaceTypes() { + return _interfaces; + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append(getName()); + buf.append(":"); + for (Class intf: _interfaces) { + buf.append(" " + intf.getName()); + } + return buf.toString(); + } + + @Override + public boolean equals(Object aObj) { + return this == aObj; + /* + if ( !(aObj instanceof DefaultProvidedInterface)) { + return false; + } + DefaultProvidedInterface provided = (DefaultProvidedInterface)aObj; + return getEqualsRepresentation().equals(provided.getEqualsRepresentation()); + */ + } + + @Override + public int hashCode() { + return getEqualsRepresentation().hashCode(); + } + + @Override + public boolean covers(ProvidedInterface aInterface) { + // TODO do more than just equals. + if ( !(aInterface instanceof DefaultProvidedInterface)) { + return false; + } + return getEqualsRepresentation().equals(((DefaultProvidedInterface)aInterface).getEqualsRepresentation()); + } + + + private String getEqualsRepresentation() { + List 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/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java new file mode 100644 index 00000000..4e0db74b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultRequiredInterface.java @@ -0,0 +1,142 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.Arrays; + +import org.wamblee.reflection.ReflectionUtils; + +public class DefaultRequiredInterface implements RequiredInterface { + + private String _name; + private boolean _optional; + private Class[] _required; + private ProvidedInterface _provider; + + public DefaultRequiredInterface(String aName, Class aInterface) { + this(aName, new Class[] { aInterface }); + } + + public DefaultRequiredInterface(String aName, Class[] aInterfaces) { + this(aName, aInterfaces, false); + } + + public DefaultRequiredInterface(String aName, Class aInterface, boolean aIsOptional) { + this(aName, new Class[] { aInterface }, aIsOptional ); + } + + + public DefaultRequiredInterface(String aName, Class[] aInterfaces, boolean aIsOptional) { + _name = aName; + _optional = aIsOptional; + _required = aInterfaces; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean isOptional() { + return _optional; + } + + @Override + public boolean implementedBy(ProvidedInterface aDescriptor) { + Class[] provided = aDescriptor.getInterfaceTypes(); + for (Class required : _required) { + if ( !serviceProvided(required, provided)) { + return false; + } + } + // all required interfaces are provided. + return true; + } + + /** + * Check if the required interface is implemented by one of the provided interfaces. + * @param aRequired required interface + * @param aProvided Provided interfaces. + * @return + */ + private boolean serviceProvided(Class aRequired, Class[] aProvided) { + for (Class provided: aProvided) { + try { + provided = ReflectionUtils.wrapIfNeeded(provided); + aRequired = ReflectionUtils.wrapIfNeeded(aRequired); + provided.asSubclass(aRequired); + return true; + } catch (ClassCastException e) { + // No match, try the next one. + } + } + return false; + } + + @Override + public ProvidedInterface getProvider() { + return _provider; + } + + @Override + public void setProvider(ProvidedInterface aProvider) { + assert aProvider != null; + assert implementedBy(aProvider); + _provider = aProvider; + } + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public boolean covers(RequiredInterface obj) { + // TODO do more than equals. + if ( !(obj instanceof DefaultRequiredInterface)) { + return false; + } + DefaultRequiredInterface descr = (DefaultRequiredInterface)obj; + if ( _required.length != descr._required.length ) { + return false; + } + String[] interfaces1 = new String[_required.length]; + String[] interfaces2 = new String[_required.length]; + for (int i = 0; i < _required.length; i++) { + interfaces1[i] = _required[i].getName(); + interfaces2[i] = descr._required[i].getName(); + } + Arrays.sort(interfaces1); + Arrays.sort(interfaces2); + return Arrays.equals(interfaces1, interfaces2); + } + + @Override + public int hashCode() { + return _required.hashCode(); + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("." + getName() + ":"); + for (Class intf: _required) { + buf.append("." + intf.getName()); + } + return buf.toString(); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java new file mode 100644 index 00000000..50c6cc3b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/DefaultScope.java @@ -0,0 +1,111 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DefaultScope implements Scope { + + private List _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 provided = _provided.get(aInterface); + if (provided == null) { + for (Scope parent : _parents) { + T impl = parent.getInterfaceImplementation(aInterface, aType); + if ( impl != null ) { + return impl; + } + } + return null; + } else { + return provided.getImplementation(aType); + } + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java new file mode 100644 index 00000000..9800621e --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/NamedInterface.java @@ -0,0 +1,23 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +public interface NamedInterface { + /** + * Name for the interface. + */ + String getName(); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java new file mode 100644 index 00000000..f09a5270 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/ProvidedInterface.java @@ -0,0 +1,42 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.Collection; + +/** + * Represents an interface provided by a component. + * Different component objects should never share ProvidedInterface instances! + * + * @author Erik Brakkee + */ +public interface ProvidedInterface extends NamedInterface { + + /** + * Returns the service type. + * @return Service type. + */ + Class[] getInterfaceTypes(); + + + /** + * Determines whether the current provided interface exceeds the given provided interface. + * In other words if it can provide at least what the given provided interface can provide. + * @param aInterface Interface to compare to. + * @return True if the current interface exceeds the given provided interface. + */ + boolean covers(ProvidedInterface aInterface); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java new file mode 100644 index 00000000..abeb70d5 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/ProvidedInterfaceImplementation.java @@ -0,0 +1,53 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +/** + * Represents a provided interface together with its implementation. + * + * @author Erik Brakkee + */ +class ProvidedInterfaceImplementation { + + private ProvidedInterface _provided; + private Object _implementation; + + /** + * Constructs the object. + * @param aProvided Provided interface. + * @param aImplementation Implementation. + */ + public ProvidedInterfaceImplementation(ProvidedInterface aProvided, Object aImplementation) { + _provided = aProvided; + _implementation = aImplementation; + } + + /** + * @return The provided interface. + */ + public ProvidedInterface getProvided() { + return _provided; + } + + /** + * @param Expected type of the implementation. + * @param aType Type of the implementation. + * @return Implementation. + */ + public T getImplementation(Class aType) { + return (T)_implementation; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java new file mode 100644 index 00000000..4dd77fc7 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/RequiredInterface.java @@ -0,0 +1,50 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +public interface RequiredInterface extends NamedInterface { + + /** + * @return True iff the required interface is optional. + */ + boolean isOptional(); + + + /** + * Checks if the service is provided by a given provided interface. + * @param aInterface Provided interface. + * @return + */ + boolean implementedBy(ProvidedInterface aInterface); + + /** + * Sets the provider of this interface. + * @param aProvider Provider. + */ + void setProvider(ProvidedInterface aProvider); + + /** + * Gets the provider interface. + * @return Provider or null if not set. + */ + ProvidedInterface getProvider(); + + /** + * Determines if the requirements of the current interface are at least those + * of the given required interface. + */ + boolean covers(RequiredInterface aInterface); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/Scope.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/Scope.java new file mode 100644 index 00000000..fe83e857 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/Scope.java @@ -0,0 +1,86 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.List; + +/** + * A scope represents a set of running services and the runtime information for the + * started components and is (usually) the result of + * starting a container. + * + * @author Erik Brakkee + */ +public interface Scope { + + /** + * Gets the provided interfaces by this scope. + * @return Provided interfaces. + */ + List 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 ); + + /** + * Gets the runtime for a component. + * @param aComponent Component for which we want to get the runtime. + * @return Runtime. + */ + Object getRuntime(Component aComponent); + + /** + * Gets the runtime for a component based on the name of the component + * (excluding its context). + * @param aName Component name. + * @return Component name. + */ + Object getRuntime(String aName); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java new file mode 100644 index 00000000..a8a0ac16 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/core/SystemAssemblyException.java @@ -0,0 +1,41 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +/** + * Exception thrown when an error occurs in assembling the systems. + * + * @author Erik Brakkee + */ +public class SystemAssemblyException extends RuntimeException { + + /** + * Constructs the exception. + * @param aMsg Message. + */ + public SystemAssemblyException(String aMsg) { + super(aMsg); + } + + /** + * Constructs the exception. + * @param aMsg Message + * @param aCause Cause. + */ + public SystemAssemblyException(String aMsg, Throwable aCause) { + super(aMsg, aCause); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java new file mode 100644 index 00000000..692c881f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/CompositeEdgeFilter.java @@ -0,0 +1,43 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +import java.util.ArrayList; +import java.util.List; + +public class CompositeEdgeFilter implements EdgeFilter { + + private List _filters; + + public CompositeEdgeFilter() { + _filters = new ArrayList(); + } + + public void add(EdgeFilter aFilter) { + _filters.add(aFilter); + } + + @Override + public boolean isViolated(Edge aEdge) { + for (EdgeFilter filter: _filters) { + if ( filter.isViolated(aEdge) ) { + return true; + } + } + return false; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java new file mode 100644 index 00000000..35d648ff --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/DefaultEdge.java @@ -0,0 +1,50 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +/** + * Represents an application-independent edge of a graph. + * Applications might choose to implement the Edge interface + * directly. + * + * @author Erik Brakkee + */ +public class DefaultEdge implements Edge { + + private Node _from; + private Node _to; + + public DefaultEdge(Node aFrom, Node aTo) { + _from = aFrom; + _to = aTo; + } + + @Override + public Node getFrom() { + return _from; + } + + @Override + public Node getTo() { + return _to; + } + + @Override + public String toString() { + return "Edge(" + _from.getName() + ", " + _to.getName() + ")"; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java new file mode 100644 index 00000000..925c08c1 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/DefaultNode.java @@ -0,0 +1,57 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +/** + * Default application-independent node. Specific applications of the graph might + * implement the Node interface directly. + * @author Erik Brakkee + * + */ +public class DefaultNode implements Node { + + private String _name; + + /** + * Constructs the node. + * @param aName Node name. + */ + public DefaultNode(String aName) { + _name = aName; + } + + /** + * Returns the node name. + */ + @Override + public String getName() { + return _name; + } + + @Override + public boolean equals(Object aObj) { + if ( !(aObj instanceof Node)) { + return false; + } + Node node = (Node)aObj; + return _name.equals(node.getName()); + } + + @Override + public int hashCode() { + return _name.hashCode(); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Edge.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Edge.java new file mode 100644 index 00000000..a340015a --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Edge.java @@ -0,0 +1,34 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +/** + * Represents an edge of a graph. + * + * @author Erik Brakkee + */ +public interface Edge { + + /** + * @return The from part of the edge. + */ + Node getFrom(); + + /** + * @return The to part of the edge. + */ + Node getTo(); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java new file mode 100644 index 00000000..4ac39f6f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +import java.util.List; + +/** + * Edge factory used to extend a graph with new edges. + * @author Erik Brakkee + * + * @param Type of node. + */ +public interface EdgeFactory { + /** + * 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); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java new file mode 100644 index 00000000..b372f082 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeFilter.java @@ -0,0 +1,21 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +public interface EdgeFilter { + + boolean isViolated(Edge aEdge); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java new file mode 100644 index 00000000..c49f82c1 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/EdgeSelector.java @@ -0,0 +1,37 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +public class EdgeSelector { + + public static interface Selector { + void execute(FromType aFrom, ToType aTo); + } + + private Class _fromType; + private Class _toType; + + public EdgeSelector(Class aFrom, Class 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()); + } + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Graph.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Graph.java new file mode 100644 index 00000000..0e4f6ccb --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Graph.java @@ -0,0 +1,243 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Represents a graph consisting of nodes and edges. + * + * @author Erik Brakkee + */ +public class Graph { + + private List _nodes; + private List _edges; + + /** + * Constructs the graph. + */ + public Graph() { + _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. + */ + public void addNode(Node aNode) { + if (_nodes.contains(aNode)) { + throw new IllegalArgumentException("Node '" + aNode.getName() + + "' already exists"); + } + _nodes.add(aNode); + } + + /** + * Finds a node with the given name. + * + * @param aName + * Node name. + * @return Node or null if not found. + */ + public Node findNode(String aName) { + for (Node node : _nodes) { + if (node.getName().equals(aName)) { + return node; + } + } + return null; + } + + /** + * Removes a node. + * + * @param aNode + * Node to remove. + * @return True iff the node was removed. + * @throws IllegalArgumentException + * In case there are edges of which the node is a part. + */ + public boolean removeNode(Node aNode) { + if (!findOutgoing(aNode).isEmpty() || !findIncoming(aNode).isEmpty()) { + throw new IllegalArgumentException("Cannot remove node '" + + aNode.getName() + + "' because it is connected to one or more edges"); + } + return _nodes.remove(aNode); + } + + /** + * Adds a list of nodes. + * + * @param aNodes + * Nodes to add. + * + * @see #addNode(Node) + */ + public void addNodes(List aNodes) { + for (Node node : aNodes) { + addNode(node); + } + } + + /** + * Adds an edge. + * + * @param aEdge + * Edge to add. + * @throws IllegalArgumentException + * In case one of the nodes of the edges is not part of the + * graph or if the same edge (as determined by + * {@link #equals(Object)} is already a part of the graph. + */ + public void addEdge(Edge aEdge) { + if (_edges.contains(aEdge)) { + throw new IllegalArgumentException("Edge '" + aEdge + + "' already exists"); + } + if (!_nodes.contains(aEdge.getFrom())) { + throw new IllegalArgumentException("From node '" + aEdge.getFrom() + + "' from edge '" + aEdge + "' is not part of the graph"); + } + if (!_nodes.contains(aEdge.getTo())) { + throw new IllegalArgumentException("To node '" + aEdge.getTo() + + "' from edge '" + aEdge + "' is not part of the graph"); + } + _edges.add(aEdge); + } + + /** + * Removes an edge. + * @param aEdge Edge to remove. + * @return True if the edge was removed. + */ + public boolean removeEdge(Edge aEdge) { + return _edges.remove(aEdge); + } + + /** + * Adds a number of edges. + * @param aEdges Edges to add. + */ + public void addEdges(List aEdges) { + for (Edge edge : aEdges) { + addEdge(edge); + } + } + + /** + * 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. + */ + 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. + */ + public void extend(EdgeFactory aFactory) { + for (Node from : _nodes) { + for (Node to : _nodes) { + _edges.addAll(aFactory.create(from, to)); + } + } + } + + /** + * Applies a filter to the graph for removing elements. + * @param aFilter Filter to apply. + */ + public void applyFilter(EdgeFilter aFilter) { + for (Iterator edge = _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. + */ + 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. + */ + 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. + */ + 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. + List edges = getEdges(); // copy ..... (see above). + + for (Node node : nodes) { + aVisitor.visitNode(node); + } + for (Edge edge : edges) { + aVisitor.visitEdge(edge); + } + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Node.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Node.java new file mode 100644 index 00000000..d1df3c03 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Node.java @@ -0,0 +1,30 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +/** + * Represents a node in a graph. + * @author Erik Brakkee + */ +public interface Node { + + /** + * Gets the node name uniquely identifying the node in the graph. + * @return Node name. + */ + String getName(); + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Visitor.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Visitor.java new file mode 100644 index 00000000..e65a535c --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/Visitor.java @@ -0,0 +1,36 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +/** + * Visitor of a graph. + * @author Erik Brakkee. + * + */ +public interface Visitor { + + /** + * Visits a node. Called by {@link Graph#accept(Visitor)}. + * @param aNode Node to visit. + */ + void visitNode(Node aNode); + + /** + * Visits a node. Called by {@link Graph#accept(Visitor)}. + * @param aEdge Edge to visit. + */ + void visitEdge(Edge aEdge); +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java new file mode 100644 index 00000000..c921630b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyProvidedVisitor.java @@ -0,0 +1,74 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.List; + +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.Graph; +import org.wamblee.system.graph.Node; +import org.wamblee.system.graph.Visitor; + +/** + * Visitor that checks whether all externally provided interfaces are actually provided + * by any of the internal components. + * + * @author Erik Brakkee + * + */ +public class CheckExternallyProvidedVisitor implements Visitor { + + private Graph _graph; + + /** + * Constructs the visitor. + * @param aGraph Component graph. + */ + public CheckExternallyProvidedVisitor(Graph aGraph) { + _graph = aGraph; + } + + @Override + public void visitEdge(Edge aEdge) { + // Empty. + } + + @Override + public void visitNode(Node aNode) { + if ( aNode instanceof ExternalProvidedInterfaceNode) { + ExternalProvidedInterfaceNode provided = (ExternalProvidedInterfaceNode) aNode; + List edges = _graph.findOutgoing(provided); + if ( edges.size() > 2 ) { + createDuplicateException("External provided interfaces has multiple internal matches", aNode, edges); + } + if ( edges.size() == 0 ) { + throw new SystemAssemblyException(aNode + ": external provded interface is not provided by any of the internal components"); + } + } + } + + private void createDuplicateException(String aMsg, Node aNode, List edges) { + StringBuffer buf = new StringBuffer(); + buf.append(aNode + + ": " + aMsg + ": "); + for (Edge edge : edges) { + buf.append(edge.getTo() + "/ "); + } + throw new SystemAssemblyException(buf.toString()); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java new file mode 100644 index 00000000..1ce53d07 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckExternallyRequiredVisitor.java @@ -0,0 +1,80 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.Graph; +import org.wamblee.system.graph.Node; +import org.wamblee.system.graph.Visitor; + +/** + * Visitor that checks whether all required external interfaces of the container + * are provided. + * + * @author Erik Brakkee + * + */ +public class CheckExternallyRequiredVisitor implements Visitor { + + private Log LOG = LogFactory.getLog(CheckExternallyRequiredVisitor.class); + + private Graph _graph; + + public CheckExternallyRequiredVisitor(Graph aGraph) { + _graph = aGraph; + } + + @Override + public void visitEdge(Edge aEdge) { + // Empty. + } + + @Override + public void visitNode(Node aNode) { + if (aNode instanceof ExternalRequiredInterfaceNode) { + ExternalRequiredInterfaceNode required = (ExternalRequiredInterfaceNode) aNode; + if (!required.getRequired().isOptional() + && required.getRequired().getProvider() == null) { + throw new SystemAssemblyException(aNode + + ": External required interface is not provided"); + } + + List edges = _graph.findIncoming(aNode); + + if (edges.isEmpty()) { + LOG.warn(aNode + ": Superfluous required interface"); + } + for (Edge edge : edges) { + Node from = edge.getFrom(); + assert from instanceof RequiredInterfaceNode; + RequiredInterfaceNode reqNode = (RequiredInterfaceNode)from; + if (!reqNode.getRequired().isOptional() + && required.getRequired().isOptional()) { + throw new SystemAssemblyException( + aNode + + ": externally required interface is optional but a corresponding internal required interface is mandatory: " + + reqNode); + } + } + } + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java new file mode 100644 index 00000000..608dfc16 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckRequiredProvidedMultiplicityVisitor.java @@ -0,0 +1,86 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.List; + +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.Graph; +import org.wamblee.system.graph.Node; +import org.wamblee.system.graph.Visitor; + +/** + * Visitor that checks whether required and provided interfaces are matched + * appropriately: + *
    + *
  • 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 { + + private Graph _graph; + + public CheckRequiredProvidedMultiplicityVisitor(Graph aGraph) { + _graph = aGraph; + } + + @Override + public void visitEdge(Edge aEdge) { + // Empty + } + + @Override + public void visitNode(Node aNode) { + if (aNode instanceof RequiredInterfaceNode) { + RequiredInterfaceNode required = (RequiredInterfaceNode) aNode; + List edges = _graph.findOutgoing(aNode); + if (edges.size() > 1) { + createDuplicateException("Multiple providers of required interface found", aNode, edges); + } + if (edges.size() == 0 && !required.getRequired().isOptional()) { + throw new SystemAssemblyException( + aNode + + ": mandatpory required interface not provided by other components started earlier"); + } + } else if ( aNode instanceof ExternalProvidedInterfaceNode) { + List edges = _graph.findOutgoing(aNode); + if ( edges.size() > 1) { + createDuplicateException("multiple internal matches for externally provided interface", aNode, edges); + } + if ( edges.size() == 0 ) { + throw new SystemAssemblyException(aNode + ": external provided interface is not provided internally"); + } + } + } + + private void createDuplicateException(String aMsg, Node aNode, List edges) { + StringBuffer buf = new StringBuffer(); + buf.append(aNode + + ": " + aMsg + ": "); + for (Edge edge : edges) { + buf.append(edge.getTo() + "/ "); + } + throw new SystemAssemblyException(buf.toString()); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java new file mode 100644 index 00000000..61f4e704 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/CheckStartupDependenciesVisitor.java @@ -0,0 +1,67 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.Graph; +import org.wamblee.system.graph.Node; +import org.wamblee.system.graph.Visitor; + +/** + * Checks whether the given component graph can be started in component + * order without any missing dependencies. + * @author Erik Brakkee + * + */ +public class CheckStartupDependenciesVisitor implements Visitor { + + private Graph _graph; + private List _available; + + /** + * Constructs the visitor. + * @param aGraph Graph. + */ + public CheckStartupDependenciesVisitor(Graph aGraph) { + _graph = aGraph; + _available = new ArrayList(); + } + + @Override + public void visitEdge(Edge aEdge) { + // Empty + } + + @Override + public void visitNode(Node aNode) { + List edges = _graph.findOutgoing(aNode); + + // check dependencies. + for (Edge edge: edges) { + Node dep = edge.getTo(); + if ( !_available.contains(dep)) { + throw new SystemAssemblyException(aNode + ": required dependency '" + dep + "' was not started"); + } + } + + _available.add(aNode); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java new file mode 100644 index 00000000..b41c41c8 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ComponentGraph.java @@ -0,0 +1,154 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.general.Pair; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.graph.CompositeEdgeFilter; +import org.wamblee.system.graph.DefaultEdge; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.Graph; +import org.wamblee.system.graph.Node; + +/** + * Represents a component graph and provides the bridge from the + * component model to a graph model. The graph model is easier + * to work with to implement specific actions and validations than + * the component model. + */ +public class ComponentGraph extends Graph { + + private boolean _isLinked; + private CompositeEdgeFilter _edgeFilter; + + /** + * Constructs an empty component graph. + */ + public ComponentGraph() { + _isLinked = false; + _edgeFilter = new CompositeEdgeFilter(); + } + + /** + * Adds an externally required interface of a container. + * This should be called before any components of the container are + * added. + * @param aComponent Component requiring the interface. + * @param aInterface Required interface. + */ + public void addRequiredInterface(Component aComponent, RequiredInterface aInterface) { + addNode(new ExternalRequiredInterfaceNode(aComponent, aInterface)); + } + + /** + * Adds an externally provided interface of a container. + * This should be called after all components of the container have been added. + * @param aComponent Component providing the interface. + * @param aInterface Provided interface. + */ + public void addProvidedInterface(Component aComponent, ProvidedInterface aInterface) { + addNode(new ExternalProvidedInterfaceNode(aComponent, aInterface)); + } + + /** + * Validates the component graph. + */ + public void validate() { + extend(new RequiredProvidedEdgeFactory()); + applyFilter(_edgeFilter); + accept(new CheckRequiredProvidedMultiplicityVisitor(this)); + accept(new CheckExternallyRequiredVisitor(this)); + accept(new CheckExternallyProvidedVisitor(this)); + accept(new CheckStartupDependenciesVisitor(this)); + } + + /** + * Links provided and required interfaces together in the component + * model based on the graph model. + */ + public void link() { + if ( _isLinked ) { + return; + } + accept(new LinkVisitor()); + _isLinked = true; + } + + /** + * Finds a list of mappings of external provided interface to internal provided interface. + * + * @return List of pairs of external to internal interface. + */ + public List> 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; + } + + /** + * Adds a component by adding required interfaces, components, and + * provided interfaces. + * @param aComponent Component to add. + */ + public void addComponent(Component aComponent) { + // Add required interfaces. + Node compNode = new ComponentNode(aComponent); + List requiredNodes = new ArrayList(); + for (RequiredInterface required: aComponent.getRequiredInterfaces()) { + Node reqNode = new RequiredInterfaceNode(aComponent, required); + addNode(reqNode); + requiredNodes.add(reqNode); + } + // Add the component + addNode(compNode); + + // Edges from component to required interface. + for (Node reqNode: requiredNodes) { + addEdge(new DefaultEdge(compNode, reqNode)); + } + + // Add provided interfaces + List providedNodes = new ArrayList(); + for (ProvidedInterface provided: aComponent.getProvidedInterfaces()) { + Node provNode = new ProvidedInterfaceNode(aComponent, provided); + addNode(provNode); + providedNodes.add(provNode); + } + + // Edges from provided interface to component + for (Node provNode: providedNodes) { + addEdge(new DefaultEdge(provNode, compNode)); + } + } + + public void addEdgeFilter(CompositeEdgeFilter aEdgeFilter) { + _edgeFilter.add(aEdgeFilter); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java new file mode 100644 index 00000000..dc344268 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ComponentNode.java @@ -0,0 +1,42 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.Component; +import org.wamblee.system.graph.Node; + +/** + * Represents a component node. + * @author Erik Brakkee. + * + */ +public class ComponentNode implements Node { + + private Component _component; + + public ComponentNode(Component aComponent) { + _component = aComponent; + } + + @Override + public String getName() { + return _component.getQualifiedName(); + } + + public Component getComponent() { + return _component; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java new file mode 100644 index 00000000..1007ae70 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedFilter.java @@ -0,0 +1,71 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFilter; + +/** + * Filter used to explicitly connect required and provided interfaces within a + * container. + * + * @author Erik Brakkee + * + */ +public class ConnectExternalProvidedProvidedFilter implements EdgeFilter { + + private String _externalProvided; + private String _component; + private String _provided; + + public ConnectExternalProvidedProvidedFilter(String aExternalProvided, String aComponent, + String aProvided) { + _externalProvided = aExternalProvided; + _component = aComponent; + _provided = aProvided; + if ( _externalProvided == null ) { + throw new IllegalArgumentException("External provided interface name must be specified."); + } + if ( _component == null ) { + throw new IllegalArgumentException("Component name must be specified"); + } + if ( _provided == null ) { + throw new IllegalArgumentException("Provided interface name of internal component must be specified"); + } + } + + @Override + public boolean isViolated(Edge aEdge) { + if (aEdge.getFrom() instanceof ExternalProvidedInterfaceNode + && aEdge.getTo() instanceof ProvidedInterfaceNode) { + return isViolated((ExternalProvidedInterfaceNode) aEdge.getFrom(), + (ProvidedInterfaceNode) aEdge.getTo()); + } + return false; + } + + private boolean isViolated(ExternalProvidedInterfaceNode aFrom, + ProvidedInterfaceNode aTo) { + if ( !aFrom.getName().equals(_externalProvided)) { + return false; // wrong provided interface. + } + if ( aTo.getComponent().getName().equals(_component) && + aTo.getProvided().getName().equals(_provided) ) { + return false; // ok + } + return true; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java new file mode 100644 index 00000000..c7084028 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilter.java @@ -0,0 +1,74 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFilter; + +/** + * Filter used to explicitly connect required and provided interfaces within a + * container. + * + * @author Erik Brakkee + * + */ +public class ConnectRequiredExternallyRequiredEdgeFilter implements EdgeFilter { + + private String _client; + private String _required; + private String _externalRequired; + + public ConnectRequiredExternallyRequiredEdgeFilter(String aClient, String aRequired, + String aExternalRequired) { + _client = aClient; + _required = aRequired; + _externalRequired = aExternalRequired; + if ( _client == null ) { + throw new IllegalArgumentException("Client component must be specified"); + } + if ( _required == null ) { + throw new IllegalArgumentException("Required interface must be specified"); + } + if ( _externalRequired == null ) { + throw new IllegalArgumentException("External required interface must be specified"); + } + } + + @Override + public boolean isViolated(Edge aEdge) { + if (aEdge.getFrom() instanceof RequiredInterfaceNode + && aEdge.getTo() instanceof ExternalRequiredInterfaceNode) { + return isViolated((RequiredInterfaceNode) aEdge.getFrom(), + (ExternalRequiredInterfaceNode) aEdge.getTo()); + } + return false; + } + + private boolean isViolated(RequiredInterfaceNode aFrom, + ExternalRequiredInterfaceNode aTo) { + if ( !aFrom.getComponent().getName().equals(_client)) { + return false; // wrong component. + } + if ( !(_required == null || aFrom.getRequired().getName().equals(_required))) { + return false; // wrong interface + } + if ( !aTo.getRequired().getName().equals(_externalRequired)) { + return true; // wrong externally required interface. + } + + return false; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java new file mode 100644 index 00000000..a1d2481f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilter.java @@ -0,0 +1,80 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFilter; + +/** + * Filter used to explicitly connect required and provided interfaces within a + * container. + * + * @author Erik Brakkee + * + */ +public class ConnectRequiredProvidedEdgeFilter implements EdgeFilter { + + private String _client; + private String _required; + private String _server; + private String _provided; + + public ConnectRequiredProvidedEdgeFilter(String aClient, String aRequired, + String aServer, String aProvided) { + _client = aClient; + _required = aRequired; + _server = aServer; + _provided = aProvided; + if ( _client == null ) { + throw new IllegalArgumentException("Client component must be specified"); + } + } + + @Override + public boolean isViolated(Edge aEdge) { + if (aEdge.getFrom() instanceof RequiredInterfaceNode + && aEdge.getTo() instanceof ProvidedInterfaceNode) { + return isViolated((RequiredInterfaceNode) aEdge.getFrom(), + (ProvidedInterfaceNode) aEdge.getTo()); + } + return false; + } + + private boolean isViolated(RequiredInterfaceNode aFrom, + ProvidedInterfaceNode aTo) { + if (_client.equals(aFrom.getComponent().getName()) + && (_required == null || _required.equals(aFrom.getRequired() + .getName()))) { + // From part matches. + if ( _server == null ) { + return true; // all connections are eliminated + } + if (_server.equals(aTo.getComponent().getName()) + && (_provided == null || _provided.equals(aTo.getProvided() + .getName()))) { + // to part matches also + return false; + } + else { + // From matches and to doesn't so edgefilter is violated. + return true; + } + } else { + // From part does not match, restriction does not apply. + return false; + } + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java new file mode 100644 index 00000000..c7fd7d0b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ExternalProvidedInterfaceNode.java @@ -0,0 +1,54 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.Component; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.graph.Node; + +/** + * Represents an external provided interface of a container. + * @author Erik Brakkee + * + */ +public class ExternalProvidedInterfaceNode implements Node { + + private Component _component; + private ProvidedInterface _provided; + + public ExternalProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) { + _component = aComponent; + _provided = aProvided; + } + + @Override + public String getName() { + return _provided.getName(); + } + + public Component getComponent() { + return _component; + } + + public ProvidedInterface getProvided() { + return _provided; + } + + @Override + public String toString() { + return _component.getQualifiedName() + ":" + _provided; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java new file mode 100644 index 00000000..5c65ebdb --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ExternalRequiredInterfaceNode.java @@ -0,0 +1,54 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.Component; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.graph.Node; + +/** + * Represents an externally required interface of a container. + * @author Erik Brakkee + * + */ +public class ExternalRequiredInterfaceNode implements Node { + + private Component _component; + private RequiredInterface _required; + + public ExternalRequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) { + _component = aComponent; + _required = aRequired; + } + + @Override + public String getName() { + return _required.getName(); + } + + public Component getComponent() { + return _component; + } + + public RequiredInterface getRequired() { + return _required; + } + + @Override + public String toString() { + return _component.getQualifiedName() + ":" + _required; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java new file mode 100644 index 00000000..cc2007ff --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/LinkVisitor.java @@ -0,0 +1,72 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.system.graph.DefaultEdge; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.Node; +import org.wamblee.system.graph.Visitor; + +/** + * Visitor that creates links between required and provided interfaces as + * described by the edges in the graph. + * + * Specically it links together (1) required and provided interfaces of internal component + * of a container and (2) the providers of externally required interfaces and internal required + * interfaces. + * + * @author Erik Brakkee + * + */ +public class LinkVisitor implements Visitor { + + @Override + public void visitEdge(Edge aEdge) { + Node from = aEdge.getFrom(); + Node to = aEdge.getTo(); + if (from instanceof RequiredInterfaceNode) { + RequiredInterfaceNode required = (RequiredInterfaceNode) from; + if (to instanceof ProvidedInterfaceNode) { + + ProvidedInterfaceNode provided = (ProvidedInterfaceNode) to; + required.getRequired().setProvider(provided.getProvided()); + + } else if (to instanceof ExternalRequiredInterfaceNode) { + ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) to; + ProvidedInterface provider = external.getRequired() + .getProvider(); + if (provider == null && !required.getRequired().isOptional()) { + throw new SystemAssemblyException("Mandatory interface '" + + from + "' is not provided."); + } + if ( provider != null ) { + required.getRequired().setProvider(provider); + } + } + } else if (from instanceof ProvidedInterfaceNode) { + // Provided interfaces can only be published after the system has + // started. + } + } + + @Override + public void visitNode(Node aNode) { + // Empty. + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java new file mode 100644 index 00000000..2fb2c0f7 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/ProvidedInterfaceNode.java @@ -0,0 +1,53 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.Component; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.graph.Node; + +/** + * Provided interface node. + * @author Erik Brakkee + */ +public class ProvidedInterfaceNode implements Node { + + private Component _component; + private ProvidedInterface _provided; + + public ProvidedInterfaceNode(Component aComponent, ProvidedInterface aProvided) { + _component = aComponent; + _provided = aProvided; + } + + @Override + public String getName() { + return _component.getQualifiedName() + ":" + _provided.getName(); + } + + public ProvidedInterface getProvided() { + return _provided; + } + + public Component getComponent() { + return _component; + } + + @Override + public String toString() { + return _component.getQualifiedName() + ":" + _provided; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java new file mode 100644 index 00000000..b1540512 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/RequiredInterfaceNode.java @@ -0,0 +1,54 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.Component; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.graph.Node; + +/** + * Required interface node. + * @author Erik Brakkee + * + */ +public class RequiredInterfaceNode implements Node { + + private Component _component; + private RequiredInterface _required; + + public RequiredInterfaceNode(Component aComponent, RequiredInterface aRequired) { + _component = aComponent; + _required = aRequired; + } + + @Override + public String getName() { + return _component.getQualifiedName() + ":" + _required.getName(); + } + + public RequiredInterface getRequired() { + return _required; + } + + public Component getComponent() { + return _component; + } + + @Override + public String toString() { + return _component.getQualifiedName() + ":" + _required; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java new file mode 100644 index 00000000..711501a1 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/RequiredProvidedEdgeFactory.java @@ -0,0 +1,74 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.ArrayList; +import java.util.List; + +import org.wamblee.system.graph.DefaultEdge; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFactory; +import org.wamblee.system.graph.Node; + +/** + * Factory that creates edges between required and provided interfaces. + * Speciflcally it creates: + *
    + *
  • 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 { + + public RequiredProvidedEdgeFactory() { + // Empty. + } + + @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())) { + result.add(new DefaultEdge(required, provided)); + } + } else if (aTo instanceof ExternalRequiredInterfaceNode) { + ExternalRequiredInterfaceNode external = (ExternalRequiredInterfaceNode) aTo; + if ( external.getRequired().covers(required.getRequired())) { + result.add(new DefaultEdge(required, external)); + } + } + } else if ( aFrom instanceof ProvidedInterfaceNode) { + ProvidedInterfaceNode provided = (ProvidedInterfaceNode)aFrom; + if ( aTo instanceof ExternalProvidedInterfaceNode) { + ExternalProvidedInterfaceNode external = (ExternalProvidedInterfaceNode)aTo; + if (provided.getProvided().covers(external.getProvided())) { + result.add(new DefaultEdge(external, provided)); + } + } + } + return result; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java new file mode 100644 index 00000000..f886d788 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/component/package-info.java @@ -0,0 +1,31 @@ +/** + *

Graph component package

+ * + * The graph component package provides the representation of a number of + * components {@link Component} + * their required and provided interfaces ({@link RequiredInterface} and + * {@link ProvidedInterface}), and how these are connected together. + * + * This package provides the bridge between the component model and the + * representation of the components and their connections in a graph. + * The component package provides various algorithms, filters, and + * validations that are required for the implementation of a container. + * + * The main abstractions are: + *
    + *
  • {@link ComponentGraph}: A graph of components. This provides the logic + * for creating a graph based on components.
  • + *
  • {@link ComponentNode}: A node representing a component.
  • + *
  • {@link RequiredInterfaceNode}: A node representing a required interface of a component.
  • + *
  • {@link ProvidedInterfaceNode}: A node repesenting a provided interface of a component.
  • + *
  • {@link ExternalRequiredInterfaceNode}: A node representing a required interface of a container
  • + *
  • {@link ExternalProvidedInterfaceNode}: A node representing a provided interface of a container
  • + *
+ * + */ +package org.wamblee.system.graph.component; + +import org.wamblee.system.core.Component; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; + diff --git a/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/package-info.java b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/package-info.java new file mode 100644 index 00000000..6a2318ec --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/main/java/org/wamblee/system/graph/package-info.java @@ -0,0 +1,20 @@ +/** + *

Graph package

+ * + * The graph package provides a general very simple abstraction of a graph. + * It was developed for the IOC container to represent dependences between + * components through their required and provided interfaces. + * + * The graph package supports a number of simple graph traversal operations, graph + * extension operations, and a visitor pattern. + * + * The main abstractions are: + *
    + *
  • {@link Graph}: The graph itself.
  • + *
  • {@link Node}: A node of a graph.
  • + *
  • {@link Edge}: An edge of a graph>
  • + *
  • {@link Visitor}: A visitor for implementing various operations on a graph.
  • + *
  • {@link EdgeFactory}: For extending the graph with new edges
  • + *
+ */ +package org.wamblee.system.graph; \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java new file mode 100644 index 00000000..cf67b247 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/AdapterTestCase.java @@ -0,0 +1,37 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.DefaultScope; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.test.EventTracker; + +import junit.framework.TestCase; + +public class AdapterTestCase extends TestCase { + + protected Scope _scope; + static EventTracker EVENT_TRACKER; + + @Override + protected void setUp() throws Exception { + super.setUp(); + EVENT_TRACKER = new EventTracker(); + _scope = new DefaultScope(new ProvidedInterface[0]); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java new file mode 100644 index 00000000..5e4f868f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ClassAdapterTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.container.Container; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.test.AssertionUtils; + +public class ClassAdapterTest extends AdapterTestCase { + + + public void testSimpleConstructorInjection() { + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); + ClassConfiguration x4Config = new ClassConfiguration(X4.class); + x4Config.getObjectConfig().getSetterConfig().initAllSetters(); + + ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config); + ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config); + + Container container = new Container("top", new Component[] { + x1Adapter, x4Adapter + }, new ProvidedInterface[0], new RequiredInterface[0]); + + Scope scope = container.start(); + AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" }, + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + + Object obj1 = scope.getRuntime(x1Adapter); + assertTrue(obj1 instanceof X1); + Object obj4 = scope.getRuntime(x4Adapter); + assertTrue(obj4 instanceof X4); + + X1 x1 = (X1) obj1; + X4 x4 = (X4) obj4; + + assertSame(x1, x4.getX1()); + } + + public void testConstructorAndSetterInjection() { + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); + ClassConfiguration x4Config = new ClassConfiguration(X4.class); + x4Config.getObjectConfig().getSetterConfig().initAllSetters(); + ClassConfiguration x8Config = new ClassConfiguration(X8.class); + x8Config.getObjectConfig().getSetterConfig().initAllSetters(); + + ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config); + ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config); + ClassAdapter x8Adapter = new ClassAdapter("x8", x8Config); + + Container container = new Container("top", new Component[] { + x1Adapter, x4Adapter, x8Adapter + }, new ProvidedInterface[0], new RequiredInterface[0]); + + Scope scope = container.start(); + AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", "x8(x1)", "x8.setX4(x4)" }, + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + + Object obj1 = scope.getRuntime(x1Adapter); + assertTrue(obj1 instanceof X1); + Object obj4 = scope.getRuntime(x4Adapter); + assertTrue(obj4 instanceof X4); + Object obj8 = scope.getRuntime(x8Adapter); + + X1 x1 = (X1) obj1; + X4 x4 = (X4) obj4; + X8 x8 = (X8) obj8; + + assertSame(x4, x8.getX4()); + assertSame(x1, x8.getX1()); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java new file mode 100644 index 00000000..8d5703dd --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ClassConfigurationTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.util.Collections; +import java.util.List; + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.RequiredInterfaceComparator; +import org.wamblee.test.AssertionUtils; + +public class ClassConfigurationTest extends AdapterTestCase { + + public void testConstructorConfig() { + ClassConfiguration classConfig = new ClassConfiguration(X1.class); + + ConstructorConfiguration config = classConfig.getConstructorConfig() + .greedy(); + + ProvidedInterface provided = new DefaultProvidedInterface("arg", + String.class); + List required = classConfig.getRequiredInterfaces(); + + assertEquals(1, required.size()); + assertFalse(required.get(0).isOptional()); + + required.get(0).setProvider(provided); + + _scope.publishInterface(provided, "hello"); + classConfig.create(_scope); + + AssertionUtils.assertEquals(new String[] { "x1(hello)" }, + AdapterTestCase.EVENT_TRACKER.getEvents(Thread.currentThread()) + .toArray()); + } + + public void testConstructorConfigWithSetters() { + ClassConfiguration classConfig = new ClassConfiguration(X7.class); + + classConfig.getConstructorConfig().select(Boolean.class); + classConfig.getObjectConfig().getSetterConfig().initAllSetters().values("setPort").setValue(0, 10); + + ProvidedInterface providedBoolean = new DefaultProvidedInterface("boolean", + Boolean.class); + ProvidedInterface providedHost = new DefaultProvidedInterface("host", String.class); + List required = classConfig.getRequiredInterfaces(); + + Collections.sort(required, new RequiredInterfaceComparator()); + assertEquals(2, required.size()); + assertEquals("arg0", required.get(0).getName()); + + required.get(0).setProvider(providedBoolean); + required.get(1).setProvider(providedHost); + + _scope.publishInterface(providedBoolean, true); + _scope.publishInterface(providedHost, "host.name.org"); + + Object obj = classConfig.create(_scope); + assertTrue(obj instanceof X7); + X7 x7 = (X7)obj; + assertNotNull(x7.getBoolean()); + assertTrue(x7.getBoolean()); + assertNull(x7.getHost()); + assertNull(x7.getPort()); + + classConfig.inject(_scope, obj); + + assertEquals("host.name.org", x7.getHost()); + assertEquals(10, x7.getPort().intValue()); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java new file mode 100644 index 00000000..0cec6fba --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ConstructorConfigurationTest.java @@ -0,0 +1,141 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.util.List; + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.test.AssertionUtils; + +public class ConstructorConfigurationTest extends AdapterTestCase { + + public void testGreedyUnique() { + ConstructorConfiguration config = new ConstructorConfiguration(X1.class) + .greedy(); + ProvidedInterface provided = new DefaultProvidedInterface("arg", + String.class); + List 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()); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java new file mode 100644 index 00000000..938a1222 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/DefaultContainerTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import org.wamblee.system.core.Scope; +import org.wamblee.test.AssertionUtils; + +public class DefaultContainerTest extends AdapterTestCase { + + public void testConstructorInjection() { + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + + ClassConfiguration x4Config = new ClassConfiguration(X4.class); + x4Config.getObjectConfig().getSetterConfig().initAllSetters(); + + DefaultContainer container = new DefaultContainer("top").addComponent( + "x1", x1Config).addComponent("x4", x4Config); + + Scope scope = container.start(); + AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)" }, + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + + Object obj = scope.getRuntime("x1"); + assertTrue(obj instanceof X1); + obj = scope.getRuntime("x4"); + assertTrue(obj instanceof X4); + } + + public void testConstructorInjectionAndSetterInjection() { + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + + X8 x8 = new X8(null); + EVENT_TRACKER.clear(); + + ClassConfiguration x4Config = new ClassConfiguration(X4.class); + x4Config.getObjectConfig().getSetterConfig().initAllSetters(); + + ObjectConfiguration x8Config = new ObjectConfiguration(X8.class); + x8Config.getSetterConfig().initAllSetters(); + + DefaultContainer container = new DefaultContainer("top").addComponent( + "x1", x1Config).addComponent("x4", x4Config).addComponent("x8", x8, x8Config); + + Scope scope = container.start(); + AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", + "x8.setX4(x4)"}, + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + + Object obj1 = scope.getRuntime("x1"); + assertTrue(obj1 instanceof X1); + Object obj4 = scope.getRuntime("x4"); + assertTrue(obj4 instanceof X4); + Object obj8 = scope.getRuntime("x8"); + assertSame(x8, obj8); + assertSame(obj4, x8.getX4()); + } + + public void testWrongObjectType() { + final DefaultContainer container = new DefaultContainer("top"); + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + container.addComponent("x", "y", new ObjectConfiguration(Integer.class)); + } + }, IllegalArgumentException.class); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java new file mode 100644 index 00000000..0c6825e7 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/ObjectAdapterTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.util.Collections; +import java.util.List; + +import org.wamblee.system.container.Container; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.RequiredInterfaceComparator; +import org.wamblee.system.core.Scope; +import org.wamblee.test.AssertionUtils; + +public class ObjectAdapterTest extends AdapterTestCase { + + public void testSetterInjection() { + + ClassConfiguration x1Config = new ClassConfiguration(X1.class); + x1Config.getObjectConfig().getSetterConfig().initAllSetters(); + x1Config.getConstructorConfig().getParameters().setValue(0, "hello"); + + ClassConfiguration x4Config = new ClassConfiguration(X4.class); + x4Config.getObjectConfig().getSetterConfig().initAllSetters(); + ObjectConfiguration x8Config = new ObjectConfiguration(X8.class); + x8Config.getSetterConfig().initAllSetters(); + + X1 x1 = new X1(); + X8 x8 = new X8(x1); + + ClassAdapter x1Adapter = new ClassAdapter("x1", x1Config); + ClassAdapter x4Adapter = new ClassAdapter("x4", x4Config); + ObjectAdapter x8Adapter = new ObjectAdapter("x8", x8, x8Config); + + Container container = new Container("top", new Component[] { + x1Adapter, x4Adapter, x8Adapter + }, new ProvidedInterface[0], new RequiredInterface[0]); + + EVENT_TRACKER.clear(); + Scope scope = container.start(); + AssertionUtils.assertEquals(new String[] { "x1(hello)", "x4(x1)", "x8.setX4(x4)" }, + EVENT_TRACKER.getEvents(Thread.currentThread()).toArray()); + + Object obj1 = scope.getRuntime(x1Adapter); + assertTrue(obj1 instanceof X1); + Object obj4 = scope.getRuntime(x4Adapter); + assertTrue(obj4 instanceof X4); + Object obj8 = scope.getRuntime(x8Adapter); + assertSame(x8, obj8); + + X4 x4 = (X4) obj4; + + + assertSame(x4, x8.getX4()); + assertSame(x1, x8.getX1()); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java new file mode 100644 index 00000000..aebdc3df --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/SetterConfigurationTest.java @@ -0,0 +1,364 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import javax.sql.DataSource; + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.RequiredInterfaceComparator; +import org.wamblee.test.AssertionUtils; + +public class SetterConfigurationTest extends AdapterTestCase { + + public void testOneSetter() { + SetterConfiguration config = new SetterConfiguration(X5.class); + config.initAllSetters(); + List 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(); + config.remove(X6.class.getMethod("setPort", Integer.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 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()); + } + + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X1.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X1.java new file mode 100644 index 00000000..b17a27c0 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X1.java @@ -0,0 +1,26 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X1 { + public X1() { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x1()"); + } + + public X1(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x1(" + aValue + ")"); + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X10.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X10.java new file mode 100644 index 00000000..fc8b90a5 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X10.java @@ -0,0 +1,26 @@ +package org.wamblee.system.adapters; + +public class X10 extends X6 { + + + @Override + public void setHost(String aHost) { + super.setHost(aHost); + } + + @Override + public String getHost() { + return super.getHost(); + } + + @Override + public Integer getPort() { + return super.getPort(); + } + + @Override + public void setPort(Integer aPort) { + super.setPort(aPort); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X11.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X11.java new file mode 100644 index 00000000..4ddc11eb --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X11.java @@ -0,0 +1,14 @@ +package org.wamblee.system.adapters; + +public class X11 { + + + public void setX(String aValue) { + + } + + public void setY(String aValue) { + + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X2.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X2.java new file mode 100644 index 00000000..50a59027 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X2.java @@ -0,0 +1,26 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X2 { + public X2(Integer aInteger) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aInteger + ")"); + } + + public X2(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x2(" + aValue + ")"); + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X3.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X3.java new file mode 100644 index 00000000..4601a033 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X3.java @@ -0,0 +1,26 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X3 { + public X3() { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x3()"); + } + + protected X3(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x3(" + aValue + ")"); + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X4.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X4.java new file mode 100644 index 00000000..8d086a8b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X4.java @@ -0,0 +1,30 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X4 { + + private X1 _x1; + + public X4(X1 aX1) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x4(x1)"); + _x1 = aX1; + } + + public X1 getX1() { + return _x1; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X5.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X5.java new file mode 100644 index 00000000..c0a82449 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X5.java @@ -0,0 +1,47 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X5 { + + private String _value; + private Integer _xyz; + + public X5() { + + } + + public void setValue(String aValue) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x5.setValue(" + aValue + ")"); + _value = aValue; + } + + public String getValue() { + return _value; + } + + public void doSomething() { + // Empty. + } + + private void setXyz(int aXyz) { + _xyz = aXyz; + } + + public Integer getXyz() { + return _xyz; + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X6.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X6.java new file mode 100644 index 00000000..06b7b5f5 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X6.java @@ -0,0 +1,42 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X6 { + + private String _host; + private Integer _port; + + public X6() { + + } + + public Integer getPort() { + return _port; + } + + public void setPort(Integer aPort) { + _port = aPort; + } + + public String getHost() { + return _host; + } + + public void setHost(String aHost) { + _host = aHost; + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X7.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X7.java new file mode 100644 index 00000000..50520183 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X7.java @@ -0,0 +1,47 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X7 { + + private String _host; + private Integer _port; + private Boolean _boolean; + + public X7(Boolean aBoolean) { + _boolean = aBoolean; + } + + public Boolean getBoolean() { + return _boolean; + } + + public Integer getPort() { + return _port; + } + + public void setPort(Integer aPort) { + _port = aPort; + } + + public String getHost() { + return _host; + } + + public void setHost(String aHost) { + _host = aHost; + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X8.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X8.java new file mode 100644 index 00000000..84b450f1 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X8.java @@ -0,0 +1,40 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.adapters; + +public class X8 { + + private X1 _x1; + private X4 _x4; + + public X8(X1 aX1) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x8(x1)"); + _x1 = aX1; + } + + public void setX4(X4 aX4) { + AdapterTestCase.EVENT_TRACKER.eventOccurred("x8.setX4(x4)"); + _x4 = aX4; + } + + public X4 getX4() { + return _x4; + } + + public X1 getX1() { + return _x1; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X9.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X9.java new file mode 100644 index 00000000..6b30541a --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/adapters/X9.java @@ -0,0 +1,18 @@ +package org.wamblee.system.adapters; + +public class X9 extends X5 { + + private boolean _flag; + + public X9() { + + } + + public boolean isFlag() { + return _flag; + } + + public void setFlag(boolean aFlag) { + _flag = aFlag; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java new file mode 100644 index 00000000..afcc581a --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/components/DatabaseComponent.java @@ -0,0 +1,64 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.components; + +import java.util.Properties; + +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DerbyDatabase; +import org.wamblee.system.components.ORMappingConfig.DatabaseType; +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.Scope; + +public class DatabaseComponent extends AbstractComponent { + + private static ProvidedInterface DB_PROPS = new DefaultProvidedInterface("dbProps", Properties.class); + + private Database _database; + + public DatabaseComponent(String aName, Database aDatabase) { + super(aName); + _database = aDatabase; + addProvidedInterface(DB_PROPS); + } + + @Override + protected Database doStart(Scope aScope) { + _database.start(); + + Properties props = new Properties(); + if ( _database instanceof DerbyDatabase ) { + props.put("database.type", DatabaseType.DERBY.toString()); + } else { + throw new IllegalArgumentException("Unknown database type " + _database); + } + //props.put("database.driver", _database.getDriverClassName()); + props.put("database.url", _database.getJdbcUrl()); + props.put("database.username", _database.getUsername()); + props.put("database.password", _database.getPassword()); + + addInterface(DB_PROPS, props, aScope); + return _database; + } + + @Override + protected void doStop(Database aRuntime) { + _database.stop(); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java new file mode 100644 index 00000000..4c100fcc --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/components/DatabaseComponentFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.components; + +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.system.container.Container; + +public class DatabaseComponentFactory { + + public static void addDatabaseConfig(Container aContainer) { + try { + aContainer.addComponent(new DatabaseComponent("db", + DatabaseBuilder.getDatabase())); + } catch (Exception e) { + throw new RuntimeException("Could not add database configuration", + e); + } + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/container/Application.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/container/Application.java new file mode 100644 index 00000000..9392974f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/container/Application.java @@ -0,0 +1,100 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.container; + +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.test.EventTracker; + +public class Application extends AbstractComponent { + public static RequiredInterface[] required(boolean aOptional, + String aPrefix) { + return new RequiredInterface[] { + new DefaultRequiredInterface(aPrefix + "string", String.class, + aOptional), + new DefaultRequiredInterface(aPrefix + "integer", + Integer.class, aOptional) }; + } + + public static RequiredInterface[] required(boolean aOptional) { + return required(aOptional, ""); + } + + private EventTracker _tracker; + private String _string; + private Integer _integer; + private double _random; + + public Application() { + this("application"); + } + + public Application(String aName) { + this(aName, ""); + } + + public Application(String aName, String aPrefix) { + super(aName, new ProvidedInterface[0], required(false, + aPrefix)); + _random = Math.random(); + } + + public Application(boolean aIsOptinal) { + super("application", new ProvidedInterface[0], required(true, "")); + } + + public Application(EventTracker aTracker) { + this(); + _tracker = aTracker; + } + + @Override + public Object doStart(Scope aScope) { + track("start." + getName()); + _string = aScope.getInterfaceImplementation(getRequiredInterfaces() + .get(0).getProvider(), String.class); + _integer = aScope.getInterfaceImplementation(getRequiredInterfaces() + .get(1).getProvider(), Integer.class); + return _random; + } + + public String getString() { + return _string; + } + + public Integer getInteger() { + return _integer; + } + + @Override + public void doStop(Object aRuntime) { + track("stop." + getName()); + if (_random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + _random + " but got " + aRuntime); + } + } + + private void track(String aString) { + if (_tracker == null) { + return; + } + _tracker.eventOccurred(aString); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java new file mode 100644 index 00000000..a7589fe4 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/container/ContainerTest.java @@ -0,0 +1,745 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.container; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.TestCase; + +import org.wamblee.general.Pair; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.DefaultScope; +import org.wamblee.system.core.Environment; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.core.StringComponent; +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.test.AssertionUtils; +import org.wamblee.test.EventTracker; + +public class ContainerTest extends TestCase { + + private EventTracker _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); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java new file mode 100644 index 00000000..2fd48f6e --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/AbstractComponentTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import junit.framework.TestCase; + +public class AbstractComponentTest extends TestCase { + + public void testNotAllInterfacesStarted() { + try { + Component component = new AbstractComponent("xx", + new ProvidedInterface[] { new DefaultProvidedInterface( + "xxx", String.class) }, new RequiredInterface[0]) { + @Override + protected Object doStart(Scope aScope) { + // Empty, not starting service. + return null; + } + + @Override + protected void doStop(Object aRuntime) { + // Empty. + } + }; + component.start(new DefaultScope(component.getProvidedInterfaces())); + } catch (SystemAssemblyException e) { + //e.printStackTrace(); + return; + } + fail(); + } + + public void testUnexpectedServicesStarted() { + try { + Component component = new AbstractComponent("xx", + new ProvidedInterface[0], new RequiredInterface[0]) { + @Override + protected Object doStart(Scope aScope) { + addInterface(new DefaultProvidedInterface("x", Integer.class), 100, aScope); + return null; + } + + @Override + protected void doStop(Object aRuntime) { + // Empty. + } + }; + component.start(new DefaultScope(component.getProvidedInterfaces())); + } catch (SystemAssemblyException e) { + //e.printStackTrace(); + return; + } + fail(); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java new file mode 100644 index 00000000..5bfca072 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultInterfaceDescriptorTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.io.Serializable; + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; + +import junit.framework.TestCase; + +public class DefaultInterfaceDescriptorTest extends TestCase { + + public void testOneRequiredOneProvidedMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", String.class); + RequiredInterface required = new DefaultRequiredInterface("name", String.class); + assertTrue(required.implementedBy(provided)); + } + + public void testOneRequiredOneProvidedMatchSubClass() { + ProvidedInterface provided = new DefaultProvidedInterface("name", Integer.class); + RequiredInterface required = new DefaultRequiredInterface("name", Number.class); + assertTrue(required.implementedBy(provided)); + } + + public void testOneRequiredOneProvidedNoMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", String.class); + RequiredInterface required = new DefaultRequiredInterface("name", Number.class); + assertFalse(required.implementedBy(provided)); + } + + public void testOneRequiredMultipleProvidedMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + new Class[] { String.class, Integer.class} ); + RequiredInterface required = new DefaultRequiredInterface("name", String.class); + assertTrue(required.implementedBy(provided)); + } + + private static class MyMultiple implements Runnable, Serializable { + @Override + public void run() { + // Empty + } + } + + public void testMultipleRequiredOneProvidedMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + MyMultiple.class ); + RequiredInterface required = new DefaultRequiredInterface("name", + new Class[] {Runnable.class, Serializable.class} ); + assertTrue(required.implementedBy(provided)); + } + + public void testMultipleRequiredOneProvidedNoMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + MyMultiple.class ); + RequiredInterface required = new DefaultRequiredInterface("name", + new Class[] { String.class, Runnable.class} ); + assertFalse(required.implementedBy(provided)); + } + + public void testMultipleRequiredMultipleProvidedMatch() { + ProvidedInterface provided = new DefaultProvidedInterface("name", + new Class[] { Runnable.class, Serializable.class, String.class} ); + RequiredInterface required = new DefaultRequiredInterface("name", + new Class[] {Runnable.class, Serializable.class} ); + assertTrue(required.implementedBy(provided)); + } + + public void testPrimitiveAndWrapperType() { + RequiredInterface req1 = new DefaultRequiredInterface("req1", int.class); + RequiredInterface req2 = new DefaultRequiredInterface("req1", Integer.class); + ProvidedInterface prov1 = new DefaultProvidedInterface("prov1", int.class); + ProvidedInterface prov2 = new DefaultProvidedInterface("prov2", Integer.class); + assertTrue(req1.implementedBy(prov1)); + assertTrue(req2.implementedBy(prov1)); + assertTrue(req1.implementedBy(prov2)); + assertTrue(req2.implementedBy(prov2)); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java new file mode 100644 index 00000000..139de7d3 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultRequiredInterfaceTest.java @@ -0,0 +1,27 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import junit.framework.TestCase; + +public class DefaultRequiredInterfaceTest extends TestCase { + + public void testEquals() { + assertFalse(new DefaultRequiredInterface("a", String.class) + .equals(new DefaultRequiredInterface("a", String.class))); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java new file mode 100644 index 00000000..7199c6fb --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/DefaultScopeTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import junit.framework.TestCase; + +public class DefaultScopeTest extends TestCase { + + public void testLookup() { + ProvidedInterface provider = new DefaultProvidedInterface("x", Integer.class); + Scope scope = new DefaultScope(new ProvidedInterface[0]); + + scope.publishInterface(provider, 100); + assertEquals(100, scope.getInterfaceImplementation(provider, Integer.class).intValue()); + } + + public void testNestedLookup() { + ProvidedInterface provider1 = new DefaultProvidedInterface("x", Integer.class); + Scope parent = new DefaultScope(new ProvidedInterface[0]); + + parent.publishInterface(provider1, 100); + + ProvidedInterface provider2 = new DefaultProvidedInterface("y", String.class); + Scope child = new DefaultScope(new ProvidedInterface[0], parent); + + child.publishInterface(provider2, "hallo"); + + assertFalse(provider1.equals(provider2)); + + assertEquals(100, child.getInterfaceImplementation(provider1, Integer.class).intValue()); + assertEquals("hallo", child.getInterfaceImplementation(provider2, String.class)); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/Environment.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/Environment.java new file mode 100644 index 00000000..4b791d05 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/Environment.java @@ -0,0 +1,92 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import javax.sql.DataSource; + +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.test.EventTracker; + +public class Environment extends AbstractComponent { + + 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, ""); + } + + public Environment(String aName, String aPrefix) { + super(aName, provided(aPrefix), new RequiredInterface[0]); + _random = Math.random(); + _integer = COUNT++; + } + + + + public Environment(EventTracker aTracker) { + this(); + _tracker = aTracker; + } + + public Integer getInteger() { + return _integer; + } + + public String getString() { + return getName() + ".hello"; + } + + @Override + protected Object doStart(Scope aScope) { + addInterface(getProvidedInterfaces().get(0), getString(), aScope); + addInterface(getProvidedInterfaces().get(1), getInteger(), aScope); + track("start." + getName()); + return _random; + } + + @Override + protected void doStop(Object aRuntime) { + track("stop." + getName()); + if (_random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + _random + " but got " + aRuntime); + } + } + + private void track(String aString) { + if (_tracker == null) { + return; + } + _tracker.eventOccurred(aString); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java new file mode 100644 index 00000000..acf683fe --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/IntegerComponent.java @@ -0,0 +1,82 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import javax.sql.DataSource; + +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.test.EventTracker; + +public class IntegerComponent extends AbstractComponent { + + private static final ProvidedInterface[] provided(String aPrefix) { + return new ProvidedInterface[] { + new DefaultProvidedInterface(aPrefix + "integer", Integer.class) }; + } + + private EventTracker _tracker; + private double _random; + + public IntegerComponent() { + this("environment"); + } + + public IntegerComponent(String aName) { + this(aName, ""); + } + + public IntegerComponent(String aName, String aPrefix) { + super(aName, provided(aPrefix), new RequiredInterface[0]); + _random = Math.random(); + } + + + + public IntegerComponent(EventTracker aTracker) { + this(); + _tracker = aTracker; + } + + public Integer getInteger() { + return 2; + } + + @Override + protected Object doStart(Scope aScope) { + addInterface(getProvidedInterfaces().get(1), getInteger(), aScope); + track("start." + getName()); + return _random; + } + + @Override + protected void doStop(Object aRuntime) { + track("stop." + getName()); + if (_random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + _random + " but got " + aRuntime); + } + } + + private void track(String aString) { + if (_tracker == null) { + return; + } + _tracker.eventOccurred(aString); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java new file mode 100644 index 00000000..404fec70 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/RequiredInterfaceComparator.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import java.util.Comparator; + +public class RequiredInterfaceComparator implements + Comparator { + + @Override + public int compare(RequiredInterface aO1, RequiredInterface aO2) { + return aO1.getName().compareTo(aO2.getName()); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/StringComponent.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/StringComponent.java new file mode 100644 index 00000000..7701c20b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/core/StringComponent.java @@ -0,0 +1,86 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.core; + +import javax.sql.DataSource; + +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.test.EventTracker; + +public class StringComponent extends AbstractComponent { + + private static final ProvidedInterface[] provided(String aPrefix) { + return new ProvidedInterface[] { + new DefaultProvidedInterface(aPrefix + "datasource", String.class) }; + } + + private EventTracker _tracker; + private double _random; + + public StringComponent() { + this("environment"); + } + + public StringComponent(String aName) { + this(aName, ""); + } + + public StringComponent(String aName, String aPrefix) { + super(aName, provided(aPrefix), new RequiredInterface[0]); + _random = Math.random(); + } + + + + public StringComponent(EventTracker aTracker) { + this(); + _tracker = aTracker; + } + + public Integer getInteger() { + return 2; + } + + public String getString() { + return getName() + ".hello"; + } + + @Override + protected Object doStart(Scope aScope) { + addInterface(getProvidedInterfaces().get(0), getString(), aScope); + track("start." + getName()); + return _random; + } + + @Override + protected void doStop(Object aRuntime) { + track("stop." + getName()); + if (_random != (Double) aRuntime) { + throw new IllegalArgumentException("Wrong runtime: expected " + + _random + " but got " + aRuntime); + } + } + + private void track(String aString) { + if (_tracker == null) { + return; + } + _tracker.eventOccurred(aString); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java new file mode 100644 index 00000000..c76ff97e --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; +import junit.framework.TestCase; + +import org.wamblee.system.container.Application; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.Environment; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.graph.component.ProvidedInterfaceNode; +import org.wamblee.system.graph.component.RequiredInterfaceNode; + +public class CompositeEdgeFilterTest extends TestCase { + private Application _app = new Application(); + private Environment _env = new Environment(); + + private Edge createEdge(Component aClient, RequiredInterface aRequired, + Component aServer, ProvidedInterface aProvided) { + Node from = new RequiredInterfaceNode(aClient, aRequired); + Node to = new ProvidedInterfaceNode(aServer, aProvided); + return new DefaultEdge(from, to); + } + + public void testEmpty() { + EdgeFilter restriction = new CompositeEdgeFilter(); + assertFalse(restriction.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), + _env, _env.getProvidedInterfaces().get(0)))); + } + + private void configureRestriction(EdgeFilter base, boolean aResult) { + stub(base.isViolated((Edge)anyObject())).toReturn(aResult); + } + + public void testOneRestriction() { + EdgeFilter base = mock(EdgeFilter.class); + CompositeEdgeFilter composite = new CompositeEdgeFilter(); + composite.add(base); + + // First let the base return false and verify the result. + + configureRestriction(base, false); + + assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), + _env, _env.getProvidedInterfaces().get(0)))); + + // Second let the base return true and verify the result. + configureRestriction(base, true); + + assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), + _env, _env.getProvidedInterfaces().get(0)))); + } + + + + public void testTwoRestrictions() { + EdgeFilter base1 = mock(EdgeFilter.class); + CompositeEdgeFilter composite = new CompositeEdgeFilter(); + composite.add(base1); + EdgeFilter base2 = mock(EdgeFilter.class); + composite.add(base2); + + // 1. base1 not violated and base 2 not violated -> not violated. + + configureRestriction(base1, false); + configureRestriction(base2, false); + assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), + _env, _env.getProvidedInterfaces().get(0)))); + + // 2. base 1 not violated but base 2 violated -> violated + configureRestriction(base1, false); + configureRestriction(base2, true); + + assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), + _env, _env.getProvidedInterfaces().get(0)))); + + // 3. base 1 violated -> violated and base 2 not called. + configureRestriction(base1, true); + // base 2 should not be called. + + assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), + _env, _env.getProvidedInterfaces().get(0)))); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java new file mode 100644 index 00000000..675a06bd --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/GraphTest.java @@ -0,0 +1,169 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +import java.util.Arrays; +import java.util.List; + +import static org.mockito.Mockito.*; +import org.wamblee.test.AssertionUtils; + + +import junit.framework.TestCase; + +public class GraphTest extends TestCase { + + public void testNodeMgt() { + final Graph graph = new Graph(); + assertTrue(graph.getNodes().isEmpty()); + assertTrue(graph.getEdges().isEmpty()); + + final Node x = new DefaultNode("x"); + graph.addNode(x); + assertEquals(Arrays.asList(new Node[] { x }), graph.getNodes()); + assertSame(x, graph.findNode("x")); + assertNull(graph.findNode("y")); + + assertTrue(graph.removeNode(x)); + assertTrue(graph.getNodes().isEmpty()); + + // Empty node set. + assertFalse(graph.removeNode(x)); + + Node y = new DefaultNode("y"); + graph.addNodes(Arrays.asList(new Node[] { x, y} )); + assertEquals(2, graph.getNodes().size()); + + // duplicate node + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + graph.addNode(new DefaultNode("x")); + } + }, IllegalArgumentException.class); + } + + public void testEdgeMgt() { + final Graph graph = new Graph(); + final Node x = new DefaultNode("x"); + final Node y = new DefaultNode("y"); + graph.addNode(x); + graph.addNode(y); + final Edge e = new DefaultEdge(x, y); + graph.addEdge(e); + assertEquals(Arrays.asList(new Edge[] { e }), graph.getEdges()); + + // duplicate edge. + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + graph.addEdge(e); + } + }, IllegalArgumentException.class); + + // Remove node when edge is still present + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + graph.removeNode(x); + } + }, IllegalArgumentException.class); + + + Node a = new DefaultNode("a"); + graph.addNode(a); + graph.addEdges(Arrays.asList(new Edge[] { new DefaultEdge(x, a), new DefaultEdge(y, a) })); + assertEquals(3, graph.getEdges().size()); + } + + public void testExtend() { + Graph graph = new Graph(); + graph.addNode(new MyNode("x", new String[] { "a", "b"})); + graph.addNode(new MyNode("y", new String[] { "b", "c"})); + graph.addNode(new MyNode("z", new String[] { "a", "c"})); + graph.extend(new MyEdgeFactory()); + + List edges = graph.getEdges(); + assertEquals(12, edges.size()); // 2 outgoing and 2 incoming nodes. + } + + public void testApplyFilter() { + Graph graph = new Graph(); + graph.addNode(new DefaultNode("x")); + graph.addNode(new DefaultNode("y")); + graph.addNode(new DefaultNode("z")); + graph.addEdge(new DefaultEdge(graph.findNode("x"), graph.findNode("y"))); + graph.addEdge(new DefaultEdge(graph.findNode("y"), graph.findNode("z"))); + graph.addEdge(new DefaultEdge(graph.findNode("z"), graph.findNode("x"))); + + assertEquals(3, graph.getEdges().size()); + + graph.applyFilter(new EdgeFilter() { + @Override + public boolean isViolated(Edge aEdge) { + if (aEdge.getFrom().getName().equals("x")) { + return false; + } + return true; + } + }); + + assertEquals(1, graph.getEdges().size()); + assertEquals("x", graph.getEdges().get(0).getFrom().getName()); + + } + + public void testFindIncomingOutgoing() { + Graph graph = new Graph(); + Node x = new DefaultNode("x"); + Node y = new DefaultNode("y"); + graph.addNode(x); + graph.addNode(y); + Edge e = new DefaultEdge(x,y); + graph.addEdge(e); + + List incoming = graph.findIncoming(x); + 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()); + } + + public void testAccept() { + Graph graph = new Graph(); + Node x = new DefaultNode("x"); + Node y = new DefaultNode("y"); + Edge e = new DefaultEdge(x, y); + graph.addNode(x); + graph.addNode(y); + graph.addEdge(e); + Visitor visitor = mock(Visitor.class); + + graph.accept(visitor); + verify(visitor).visitNode(x); + verify(visitor).visitNode(y); + verify(visitor).visitEdge(e); + + verifyNoMoreInteractions(visitor); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java new file mode 100644 index 00000000..daddccd6 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/MyEdgeFactory.java @@ -0,0 +1,41 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +import java.util.ArrayList; +import java.util.List; + +public class MyEdgeFactory implements EdgeFactory { + + public MyEdgeFactory() { + // Empty. + } + + @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)) { + result.add(new DefaultEdge(aFrom, aTo)); + } + } + } + + return result; + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/MyNode.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/MyNode.java new file mode 100644 index 00000000..0090c3f9 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/MyNode.java @@ -0,0 +1,30 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph; + +public class MyNode extends DefaultNode { + + private String[] _ports; + + public MyNode(String aName, String[] aPorts) { + super(aName); + _ports = aPorts; + } + + public String[] getPorts() { + return _ports; + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java new file mode 100644 index 00000000..5f45f551 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectExternalProvidedProvidedEdgeFilterTest.java @@ -0,0 +1,94 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import junit.framework.TestCase; + +import org.wamblee.system.container.Container; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.Environment; +import org.wamblee.system.graph.DefaultEdge; +import org.wamblee.system.graph.DefaultNode; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFilter; + +public class ConnectExternalProvidedProvidedEdgeFilterTest extends TestCase { + + private Container _container; + private Component _internal; + private String _externalInterfaceName; + private String _internalComponentName; + private String _internalInterfaceName; + private Edge _edge; + + @Override + protected void setUp() throws Exception { + _container = new Container("container") + .addProvidedInterface(new DefaultProvidedInterface("string", + String.class)); + _internal = new Environment("env1"); + + _externalInterfaceName = _container.getProvidedInterfaces().get(0) + .getName(); + _internalComponentName = _internal.getName(); + _internalInterfaceName = _internal.getProvidedInterfaces().get(0).getName(); + + _edge = new DefaultEdge(new ExternalProvidedInterfaceNode(_container, + _container.getProvidedInterfaces().get(0)), + new ProvidedInterfaceNode(_internal, _internal + .getProvidedInterfaces().get(0))); + } + + public void testWrongExternal() { + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( + _externalInterfaceName + "x", _internalComponentName, + _internalInterfaceName); + assertFalse(filter.isViolated(_edge)); + } + + public void testRightExternalWrongComponent() { + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( + _externalInterfaceName, _internalComponentName + "x", + _internalInterfaceName); + assertTrue(filter.isViolated(_edge)); + } + + public void testRightExternalWrongInternal() { + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( + _externalInterfaceName, _internalComponentName, + _internalInterfaceName + "x"); + assertTrue(filter.isViolated(_edge)); + } + + public void testEverythingRight() { + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( + _externalInterfaceName, _internalComponentName, + _internalInterfaceName); + assertFalse(filter.isViolated(_edge)); + } + + + public void testWrongEdgeType() { + EdgeFilter filter = new ConnectExternalProvidedProvidedFilter( + _externalInterfaceName, _internalComponentName, + _internalInterfaceName); + DefaultEdge edge = new DefaultEdge(new DefaultNode("x"), + new DefaultNode("y")); + assertFalse(filter.isViolated(edge)); + } + +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java new file mode 100644 index 00000000..7e8e02ce --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredExternallyRequiredEdgeFilterTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import junit.framework.TestCase; + +import org.wamblee.system.container.Application; +import org.wamblee.system.container.Container; +import org.wamblee.system.core.Component; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.graph.DefaultEdge; +import org.wamblee.system.graph.DefaultNode; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFilter; +import org.wamblee.system.graph.Node; + +public class ConnectRequiredExternallyRequiredEdgeFilterTest extends TestCase { + + private Component _comp; + private Container _container; + private Edge _edge; + + @Override + protected void setUp() throws Exception { + _comp = new Application(); + _container = new Container("container") + .addRequiredInterface(new DefaultRequiredInterface("x", + String.class)); + Node req = new RequiredInterfaceNode(_comp, _comp + .getRequiredInterfaces().get(0)); + Node external = new ExternalRequiredInterfaceNode(_container, + _container.getRequiredInterfaces().get(0)); + _edge = new DefaultEdge(req, external); + } + + public void testRightComponentRightInterface() { + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( + _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(), + _container.getRequiredInterfaces().get(0).getName()); + assertFalse(filter.isViolated(_edge)); + } + + public void testWrongInterface() { + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( + _comp.getName(), _comp.getRequiredInterfaces().get(0).getName() + + "xx", _container.getRequiredInterfaces().get(0).getName()); + assertFalse(filter.isViolated(_edge)); + } + + public void testWrongComponent() { + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( + _comp.getName() + "xx", _comp.getRequiredInterfaces().get(0) + .getName(), _container.getRequiredInterfaces().get(0) + .getName()); + assertFalse(filter.isViolated(_edge)); + } + + public void testWrongExternalInterface() { + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( + _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(), + _container.getRequiredInterfaces().get(0).getName() + "xx"); + assertTrue(filter.isViolated(_edge)); + } + + public void testWrongEdgeType() { + DefaultEdge edge = new DefaultEdge(new DefaultNode("x"), + new DefaultNode("y")); + EdgeFilter filter = new ConnectRequiredExternallyRequiredEdgeFilter( + _comp.getName(), _comp.getRequiredInterfaces().get(0).getName(), + _container.getRequiredInterfaces().get(0).getName()); + assertFalse(filter.isViolated(edge)); + } +} diff --git a/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java new file mode 100644 index 00000000..0cb9013b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/general/src/test/java/org/wamblee/system/graph/component/ConnectRequiredProvidedEdgeFilterTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.graph.component; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.wamblee.system.container.Application; +import org.wamblee.system.core.Environment; +import org.wamblee.system.graph.DefaultEdge; +import org.wamblee.system.graph.Edge; +import org.wamblee.system.graph.EdgeFilter; +import org.wamblee.system.graph.Node; +import org.wamblee.test.AssertionUtils; + +import junit.framework.TestCase; + +public class ConnectRequiredProvidedEdgeFilterTest extends TestCase { + + private Application _app1 = new Application("app1", "pf1."); + private Application _app2 = new Application("app2", "pf2."); + + private Environment _env1 = new Environment("env1", "pf3."); + private Environment _env2 = new Environment("env2", "pf4."); + + + private void compare(Boolean[] aExpected, EdgeFilter aRestriction) { + List 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() { + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, null, null); + + } + }, IllegalArgumentException.class); + AssertionUtils.assertException(new AssertionUtils.ErroneousCode() { + @Override + public void run() throws Exception { + EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter(null, null, "x", "y"); + } + }, IllegalArgumentException.class); + } + + public void testClientServer() { + EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1", null, "env1", null); + compare(new Boolean[] { false, false, true, false}, restriction); + } + + public void testNoConnectionsAtAll() { + EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter("app1", null, null, null); + compare(new Boolean[] { true, false, true, false}, restriction); + } + + public void testExplicitConfig() { + _app1 = new Application("app1"); + _app2 = new Application("app2"); + _env1 = new Environment("env1"); + _env2 = new Environment("env2"); + + EdgeFilter restriction = new ConnectRequiredProvidedEdgeFilter( + "app2", "string", "env1", "datasource"); + compare(new Boolean[] { false, false, false, true}, restriction); + + } +} diff --git a/tags/wamblee-utils-0.2/system/pom.xml b/tags/wamblee-utils-0.2/system/pom.xml new file mode 100644 index 00000000..81889e0e --- /dev/null +++ b/tags/wamblee-utils-0.2/system/pom.xml @@ -0,0 +1,20 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-system + pom + /system + http://wamblee.org + + general + spring + + + diff --git a/tags/wamblee-utils-0.2/system/spring/pom.xml b/tags/wamblee-utils-0.2/system/spring/pom.xml new file mode 100644 index 00000000..bc561123 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/pom.xml @@ -0,0 +1,58 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-system-spring + jar + 0.2 + /system/spring + http://wamblee.org + + + org.wamblee + wamblee-support-general + ${project.version} + + + org.wamblee + wamblee-system-general + ${project.version} + + + org.wamblee + wamblee-support-spring + ${project.version} + + + org.wamblee + wamblee-support-spring + ${project.version} + test-jar + + + org.wamblee + wamblee-hibernate-jpa + ${project.version} + + + commons-logging + commons-logging + + + org.springframework + spring-beans + + + org.springframework + spring-context + + + + + diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java new file mode 100644 index 00000000..7443b57c --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/ConfiguredProperties.java @@ -0,0 +1,30 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class ConfiguredProperties extends Properties { + + public ConfiguredProperties(String aProps) throws IOException { + InputStream is = new ByteArrayInputStream(aProps.getBytes()); + load(is); + is.close(); + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java new file mode 100644 index 00000000..f88c4054 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/PropertySetter.java @@ -0,0 +1,51 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.util.Properties; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; + +/** + * Bean that provides postprocessing of the bean factory based on + * a given set of properties. + * + * @author Erik Brakkee + */ +class PropertySetter extends PropertyPlaceholderConfigurer { + + /** + * Constructs the property setter. + * @param aProps Properties. + */ + public PropertySetter(Properties aProps) { + String propFile = createPropertyFile(aProps); + setLocation(new StringResource(propFile)); + } + + public static String createPropertyFile(Properties aProps) { + StringBuffer buf = new StringBuffer(); + for (Object key: aProps.keySet()) { + buf.append(key); + buf.append("="); + buf.append(aProps.get(key)); + buf.append("\n"); + } + return buf.toString(); + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java new file mode 100644 index 00000000..71ac3085 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/RequiredServiceBean.java @@ -0,0 +1,65 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.util.List; + +import org.springframework.beans.factory.FactoryBean; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.SystemAssemblyException; + +/** + * Bean which adds a service required by the spring component to + * the application context so that other spring beans can use it. + * + * @author Erik Brakkee + */ +class RequiredServiceBean implements FactoryBean { + + private RequiredInterface _required; + + /** + * Constructs the bean. + * @param aId Id of the bean in the service registry. + */ + public RequiredServiceBean(String aId) { + List required = SpringComponent.THIS.get().getRequiredInterfaces(); + for ( RequiredInterface intf: required) { + if ( intf.getName().equals(aId)) { + _required = intf; + return; + } + } + throw new SystemAssemblyException("Cannot resolve required component '" + aId + "'"); + } + + @Override + public Object getObject() throws Exception { + return SpringComponent.SCOPE.get().getInterfaceImplementation( + _required.getProvider(), Object.class); + } + + @Override + public Class getObjectType() { + return null; + } + + @Override + public boolean isSingleton() { + return true; + } + +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java new file mode 100644 index 00000000..88746a5e --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/SpringComponent.java @@ -0,0 +1,202 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConstructorArgumentValues; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultScope; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.core.SystemAssemblyException; + +/** + * Represents a system configured based on spring. The spring config files that + * are configured should not contain any PropertyPlaceholderConfigurer objects. + * + * @author Erik Brakkee + */ +public class SpringComponent extends AbstractComponent { + + 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 required: getRequiredInterfaces()) { + String beanName = _required.get(required); + if ( beanName != null && beanName.length() > 0) { + ConstructorArgumentValues cargs = new ConstructorArgumentValues(); + cargs.addGenericArgumentValue(required.getName()); + BeanDefinition definition = new RootBeanDefinition( + RequiredServiceBean.class, cargs, + new MutablePropertyValues()); + aParentContext.registerBeanDefinition(beanName, definition); + } else { + // The required interface is not required by the spring config but by the sub-class directly. + } + } + } + + private void registerPropertyObjects(GenericApplicationContext aParentContext) { + for (String beanName: _propertyObjects.keySet()) { + ConstructorArgumentValues cargs = new ConstructorArgumentValues(); + cargs.addGenericArgumentValue(PropertySetter.createPropertyFile(_propertyObjects.get(beanName))); + BeanDefinition definition = new RootBeanDefinition( + ConfiguredProperties.class, cargs, + new MutablePropertyValues()); + aParentContext.registerBeanDefinition(beanName, definition); + } + } + + + @Override + protected void doStop(Scope aRuntime) { + AbstractApplicationContext context = (AbstractApplicationContext)aRuntime.get(CONTEXT_KEY); + context.close(); + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java new file mode 100644 index 00000000..3f9a7919 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/StringResource.java @@ -0,0 +1,74 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import org.springframework.core.io.Resource; + +class StringResource implements Resource { + + private String _value; + + public StringResource(String aValue) { + _value = aValue; + } + + @Override + public Resource createRelative(String aRelativePath) throws IOException { + throw new IOException("No relative resource possible"); + } + + @Override + public boolean exists() { + return false; + } + + @Override + public String getDescription() { + return "Properties of a spring component"; + } + + @Override + public File getFile() throws IOException { + throw new IOException(); + } + + @Override + public String getFilename() { + return "springcomponent.properties"; + } + + @Override + public URL getURL() throws IOException { + throw new IOException(); + } + + @Override + public boolean isOpen() { + return false; + } + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(_value.getBytes()); + } + +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java new file mode 100644 index 00000000..a8d53d46 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/component/DatasourceComponent.java @@ -0,0 +1,76 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring.component; + +import java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + +import javax.sql.DataSource; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.wamblee.system.components.ORMappingConfig; +import org.wamblee.system.components.ORMappingConfig.DatabaseType; +import org.wamblee.system.core.AbstractComponent; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.SpringComponent; + +public class DatasourceComponent extends AbstractComponent { + + private static RequiredInterface PROPS = new DefaultRequiredInterface("dbprops", Properties.class); + private static ProvidedInterface DATASOURCE = new DefaultProvidedInterface("datasource", + DataSource.class); + private static ProvidedInterface ORM_CONFIG = new DefaultProvidedInterface("ormconfig", + ORMappingConfig.class); + + public DatasourceComponent(String aName) throws IOException { + super(aName); + + addRequiredInterface(PROPS); + addProvidedInterface(DATASOURCE); + addProvidedInterface(ORM_CONFIG); + } + + + @Override + protected DataSource doStart(Scope aScope) { + Properties dbProps = aScope.getInterfaceImplementation( + PROPS.getProvider(), Properties.class); + DriverManagerDataSource ds = new DriverManagerDataSource( + dbProps.getProperty("database.url"), + dbProps.getProperty("database.username"), + dbProps.getProperty("database.password")); + addInterface(DATASOURCE, ds, aScope); + DatabaseType type = DatabaseType.valueOf(dbProps.getProperty("database.type")); + + ORMappingConfig config = new ORMappingConfig(true, type); + + addInterface(ORM_CONFIG, config, aScope); + + return ds; + } + + @Override + protected void doStop(DataSource aRuntime) { + // Empty. + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java new file mode 100644 index 00000000..4b256254 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/java/org/wamblee/system/spring/component/HibernateComponent.java @@ -0,0 +1,105 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring.component; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.sql.DataSource; + +import org.hibernate.SessionFactory; +import org.hibernate.dialect.DerbyDialect; +import org.hibernate.dialect.MySQLInnoDBDialect; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.transaction.PlatformTransactionManager; +import org.wamblee.persistence.hibernate.HibernateMappingFiles; +import org.wamblee.system.components.ORMappingConfig; +import org.wamblee.system.components.ORMappingConfig.DatabaseType; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.spring.SpringComponent; + +public class HibernateComponent extends SpringComponent { + + private static final String HIBERNATE_DIALECT_PROP = "hibernate.dialect"; + private static final String HIBERNATE_SCHEMAUPDATE_PROP = "hibernate.schemaupdate"; + private static final String HIBERNATE_PROPS_KEY = "hibernateProperties"; + private static final String HIBERNATE_SPRING_CONFIG = "spring/org.wamblee.system.spring.component.hibernate.xml"; + + private final RequiredInterface CONFIG = new DefaultRequiredInterface("config", ORMappingConfig.class); + + public HibernateComponent(String aName) throws IOException { + super(aName, new String[] { HIBERNATE_SPRING_CONFIG}, + createProvided(), createRequired()); + + Properties props = new Properties(); + addProperties(HIBERNATE_PROPS_KEY, props); + + addRequiredInterface(CONFIG); + } + + @Override + protected Scope doStart(Scope aExternalScope) { + + ORMappingConfig config = aExternalScope.getInterfaceImplementation(CONFIG.getProvider(), ORMappingConfig.class); + setProperty(HIBERNATE_SCHEMAUPDATE_PROP, "" + config.isSchemaUpdate()); + + DatabaseType db = config.getType(); + String dialect = db.handleCases(new DatabaseType.Switch() { + @Override + public String handleMySqlInnoDb() { + return MySQLInnoDBDialect.class.getName(); + } + @Override + public String handleDerby() { + return DerbyDialect.class.getName(); + } + }); + getHibernateProperties().put(HIBERNATE_DIALECT_PROP, dialect); + + + return super.doStart(aExternalScope); + } + + private Properties getHibernateProperties() { + return getProperties(HIBERNATE_PROPS_KEY); + } + + private static Map createRequired() { + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("datasource", DataSource.class), "dataSource"); + required.put(new DefaultRequiredInterface("mappingFiles", HibernateMappingFiles.class), + "hibernateMappingFiles"); + return required; + } + + 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)); + return provided; + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/resources/properties/org.wamblee.system.spring.component.hibernate.properties b/tags/wamblee-utils-0.2/system/spring/src/main/resources/properties/org.wamblee.system.spring.component.hibernate.properties new file mode 100644 index 00000000..5c38ff63 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/resources/properties/org.wamblee.system.spring.component.hibernate.properties @@ -0,0 +1,15 @@ + +################################################################################### +# dialect +################################################################################### +#hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect + +################################################################################### +# hibernate cache provider +################################################################################### +#hibernate.cache.provider=org.hibernate.cache.EhCacheProvider + +################################################################################### +# query cache +################################################################################### +#hibernate.cache.use_query_cache=true \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/system/spring/src/main/resources/spring/org.wamblee.system.spring.component.hibernate.xml b/tags/wamblee-utils-0.2/system/spring/src/main/resources/spring/org.wamblee.system.spring.component.hibernate.xml new file mode 100644 index 00000000..73c02b44 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/main/resources/spring/org.wamblee.system.spring.component.hibernate.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + ${hibernate.schemaupdate} + + + + + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java new file mode 100644 index 00000000..5bbafa1d --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/BlaService.java @@ -0,0 +1,35 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +public class BlaService { + private HelloService _hello; + + public BlaService(HelloService aService) { + if ( aService == null ) { + throw new IllegalArgumentException("helloService is null"); + } + _hello = aService; + } + + public String execute() { + return _hello.say(); + } + + public void stop() { + System.out.println("Blaservice stopping"); + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java new file mode 100644 index 00000000..00002de1 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/ConfiguredPropertiesTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.io.IOException; +import java.util.Properties; + +import junit.framework.TestCase; + +public class ConfiguredPropertiesTest extends TestCase { + + public void testProps() throws IOException { + Properties props = new Properties(); + props.put("x", "y"); + props.put("a", "b"); + + ConfiguredProperties props2 = new ConfiguredProperties( + PropertySetter.createPropertyFile(props)); + + assertEquals(props.size(), props2.size()); + assertEquals(props.get("x"), props2.get("x")); + assertEquals(props.get("a"), props2.get("a")); + } +} + diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java new file mode 100644 index 00000000..cfa5bae6 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/HelloService.java @@ -0,0 +1,30 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +public class HelloService { + + private String _msg; + + public HelloService(String aMsg) { + SpringComponentTest.EVENT_TRACKER.eventOccurred(aMsg); + _msg = aMsg; + } + + public String say() { + return _msg; + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java new file mode 100644 index 00000000..e9c77080 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/HelloService2.java @@ -0,0 +1,31 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.util.Properties; + +public class HelloService2 { + + private Properties _props; + + public HelloService2(Properties aProps) { + _props = aProps; + } + + public Properties getProperties() { + return _props; + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java new file mode 100644 index 00000000..1cc95c11 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SpringComponentTest.java @@ -0,0 +1,264 @@ +/* + * Copyright 2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import junit.framework.TestCase; + +import org.wamblee.io.ClassPathResource; +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.DefaultScope; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; +import org.wamblee.system.core.SystemAssemblyException; +import org.wamblee.test.EventTracker; + +public class SpringComponentTest extends TestCase { + + private static final String HELLO_SERVICE_SPRING_XML = "test.org.wamblee.system.spring.xml"; + private static final String HELLO_SERVICE_SPRING_WITH_REQS_XML = "test.org.wamblee.system.springWithRequirements.xml"; + private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML = "test.org.wamblee.system.springWithProperties.xml"; + private static final String HELLO_SERVICE_SPRING_WITH_PROPERTIES_XML2 = "test.org.wamblee.system.springWithProperties2.xml"; + + private static final String PROPERTY_FILE = "test.org.wamblee.system.spring.properties"; + + public static EventTracker EVENT_TRACKER; + + private Scope _externalScope; + + @Override + protected void setUp() throws Exception { + super.setUp(); + EVENT_TRACKER = new EventTracker(); + _externalScope = new DefaultScope(new ProvidedInterface[0]); + } + + public void testBlackboxSystem() { + 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()); + + system.stop(runtime); + } + + public void testOneProvidedService() { + Map provided = new HashMap(); + provided.put("helloService", new DefaultProvidedInterface("hello", + HelloService.class)); + + SpringComponent system = new SpringComponent("system", + new String[] { HELLO_SERVICE_SPRING_XML }, provided, + new HashMap()); + 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); + assertSame(service, service2); + + assertEquals("Hello world!", ((HelloService) service).say()); + system.stop(runtime); + } + + public void testWithProperties() throws IOException { + Map provided = new HashMap(); + 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(); + props.load(new ClassPathResource(PROPERTY_FILE).getInputStream()); + system.addProperties(props); + + Scope scope = system.start(_externalScope); + // BUG: Hello service was constructed multiple times. Once with the + // unprocessed property + // and another time with the processed property. + assertEquals(1, EVENT_TRACKER.getEventCount()); + List services = scope.getProvidedInterfaces(); + assertEquals("Property Value", scope.getInterfaceImplementation( + services.get(0), HelloService.class).say()); + } + + public void testWithPropertiesAsBean() throws IOException { + Map provided = new HashMap(); + 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(); + props.load(new ClassPathResource(PROPERTY_FILE).getInputStream()); + system.addProperties("properties", props); + + Scope scope = system.start(_externalScope); + + List services = scope.getProvidedInterfaces(); + + Properties props2 = scope.getInterfaceImplementation(services.get(0), + HelloService2.class).getProperties(); + assertEquals(props, props2); + } + + public void testWithMissingRequirement() { + try { + SpringComponent system = new SpringComponent("system", + new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, + new HashMap(), + new HashMap()); + system.start(_externalScope); + } catch (SystemAssemblyException e) { + // e.printStackTrace(); + return; + } + fail(); + } + + public void testWithRequirement() { + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("hello", HelloService.class), + "helloService"); + SpringComponent system = new SpringComponent("system", + new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, + new HashMap(), required); + + HelloService helloObject = new HelloService("ladida"); + ProvidedInterface helloService = new DefaultProvidedInterface("hello", + HelloService.class); + Scope scope = new DefaultScope(new ProvidedInterface[] { helloService }); + scope.publishInterface(helloService, helloObject); + system.getRequiredInterfaces().get(0).setProvider(helloService); + + Scope runtime = system.start(scope); + system.stop(runtime); + } + + public void testWithRequirementAndProvidedService() { + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("hello", HelloService.class), + "helloService"); + Map provided = new HashMap(); + provided.put("blaService", new DefaultProvidedInterface("bla", + BlaService.class)); + + SpringComponent system = new SpringComponent("system", + new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, provided, + required); + + HelloService helloObject = new HelloService("ladida"); + ProvidedInterface helloService = new DefaultProvidedInterface("hello", + HelloService.class); + Scope scope = new DefaultScope(new ProvidedInterface[] { helloService }); + scope.publishInterface(helloService, helloObject); + system.getRequiredInterfaces().get(0).setProvider(helloService); + Scope runtime = system.start(scope); + ProvidedInterface started = runtime.getProvidedInterfaces().get(0); + + Object impl = runtime.getInterfaceImplementation(started, + BlaService.class); + assertNotNull(impl); + assertTrue(impl instanceof BlaService); + assertEquals("ladida", ((BlaService) impl).execute()); + system.stop(runtime); + } + + /** + * Tests a scenario where a subclass of SpringComponent adds a new provided + * interface where the interface is provided by the subclass itself and not + * by the spring configs inside. + */ + public void testWithProvidedFromSubClassNotFromConfig() { + Map provided = new HashMap(); + provided.put("helloService", new DefaultProvidedInterface("hello", + HelloService.class)); + + SubSpringComponent system = new SubSpringComponent("system", + new String[] { HELLO_SERVICE_SPRING_XML }, provided, + new HashMap()); + + 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); + assertSame(service, service2); + + Object floatsvc = _externalScope.getInterfaceImplementation(system + .getProvidedInterfaces().get(1), Object.class); + assertTrue(floatsvc instanceof Float); + assertTrue((((Float) floatsvc).floatValue() - 100.345f) < 0.00001); + + assertEquals("Hello world!", ((HelloService) service).say()); + system.stop(runtime); + } + + /** + * Tests the spring component with an additional requirement from the subclass + * which is not required by the spring config files inside. + */ + public void testWithRequirementFromSubClass() { + Map required = new HashMap(); + required.put(new DefaultRequiredInterface("hello", HelloService.class), + "helloService"); + SpringComponent system = new SubSpringComponent2("system", + new String[] { HELLO_SERVICE_SPRING_WITH_REQS_XML }, + new HashMap(), required); + + HelloService helloObject = new HelloService("ladida"); + ProvidedInterface helloService = new DefaultProvidedInterface("hello", + HelloService.class); + + ProvidedInterface floatService = new DefaultProvidedInterface("float", Float.class); + + Scope scope = new DefaultScope(new ProvidedInterface[] { helloService }); + scope.publishInterface(helloService, helloObject); + scope.publishInterface(floatService, 100.234f); + system.getRequiredInterfaces().get(0).setProvider(helloService); + system.getRequiredInterfaces().get(1).setProvider(floatService); + + Scope runtime = system.start(scope); + system.stop(runtime); + + assertEquals(100.234f, ((Float)runtime.get("floatValue")).floatValue(), 0.0001f); + } + +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java new file mode 100644 index 00000000..5e79a7ad --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent.java @@ -0,0 +1,44 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.util.Map; + + +import org.wamblee.system.core.DefaultProvidedInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +public class SubSpringComponent extends SpringComponent { + + private static ProvidedInterface PROVIDED = new DefaultProvidedInterface("provided", Float.class); + + public SubSpringComponent(String aName, String[] aConfigFiles, + Map aProvided, + Map aRequired) { + super(aName, aConfigFiles, aProvided, aRequired); + addProvidedInterface(PROVIDED); + } + + @Override + protected Scope doStart(Scope aExternalScope) { + + Scope scope = super.doStart(aExternalScope); + addInterface(PROVIDED, 100.345f, aExternalScope); + return scope; + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java new file mode 100644 index 00000000..7b67cc42 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/SubSpringComponent2.java @@ -0,0 +1,45 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.system.spring; + +import java.util.Map; + +import org.wamblee.system.core.DefaultRequiredInterface; +import org.wamblee.system.core.ProvidedInterface; +import org.wamblee.system.core.RequiredInterface; +import org.wamblee.system.core.Scope; + +public class SubSpringComponent2 extends SpringComponent { + + private static RequiredInterface REQUIRED = new DefaultRequiredInterface("required", Float.class); + + public SubSpringComponent2(String aName, String[] aConfigFiles, + Map aProvided, + Map aRequired) { + super(aName, aConfigFiles, aProvided, aRequired); + addRequiredInterface(REQUIRED); + } + + @Override + protected Scope doStart(Scope aExternalScope) { + + Scope scope = super.doStart(aExternalScope); + + float value = aExternalScope.getInterfaceImplementation(REQUIRED.getProvider(), Float.class); + scope.put("floatValue", value); + return scope; + } +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java new file mode 100644 index 00000000..b988107b --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/java/org/wamblee/system/spring/component/DatabaseTesterComponent.java @@ -0,0 +1,521 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.wamblee.system.spring.component; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.sql.DataSource; + +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.dbunit.DatabaseUnitException; +import org.dbunit.database.DatabaseConnection; +import org.dbunit.database.DatabaseSequenceFilter; +import org.dbunit.database.IDatabaseConnection; +import org.dbunit.dataset.FilteredDataSet; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.filter.ITableFilter; +import org.dbunit.operation.DatabaseOperation; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.orm.hibernate3.HibernateTemplate; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionCallbackWithoutResult; +import org.springframework.transaction.support.TransactionTemplate; +import org.wamblee.test.spring.TestTransactionCallback; +import org.wamblee.test.spring.TestTransactionCallbackWithoutResult; + +/** + * Test support class for database testing. Currently, this still requires the + * spring platform transaction manager and hibernate template. + */ +public class DatabaseTesterComponent { + + private static final Log LOG = LogFactory + .getLog(DatabaseTesterComponent.class); + + /** + * Schema pattern. + */ + private static final String SCHEMA_PATTERN = "%"; + + /** + * Cached spring application context. + */ + private ApplicationContext _context; + + private HibernateTemplate _hibernateTemplate; + + private PlatformTransactionManager _transactionManager; + + private DataSource _dataSource; + + public DatabaseTesterComponent(HibernateTemplate aHibernateTemplate, + PlatformTransactionManager aTransactionManager, + DataSource aDataSource) { + _hibernateTemplate = aHibernateTemplate; + _transactionManager = aTransactionManager; + _dataSource = aDataSource; + } + + /** + * @return Hibernate session factory. + */ + protected SessionFactory getSessionFactory() { + return _hibernateTemplate.getSessionFactory(); + } + + /** + * Performs common initialization for test cases: + *
    + *
  • Cleaning the database.
  • + *
+ * + * @throws Exception + */ + public void setUp() throws Exception { + LOG.info("Performing setUp()"); + + cleanDatabase(); + } + + /** + * Performs common tear down after execution of a test case. Currenlty this + * method does nothing. + * + * @throws Exception + */ + protected void tearDown() throws Exception { + // Empty + } + + /** + * @return Transaction manager + */ + protected PlatformTransactionManager getTransactionManager() { + return _transactionManager; + } + + /** + * @return Starts a new transaction. + */ + protected TransactionStatus getTransaction() { + DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + + return getTransactionManager().getTransaction(def); + } + + /** + * Returns the hibernate template for executing hibernate-specific + * functionality. + * + * @return Hibernate template. + */ + public HibernateTemplate getTemplate() { + return _hibernateTemplate; + } + + /** + * Flushes the session. Should be called after some Hibernate work and + * before JDBC is used to check results. + * + */ + public void flush() { + getTemplate().flush(); + } + + /** + * Flushes the session first and then removes all objects from the Session + * cache. Should be called after some Hibernate work and before JDBC is used + * to check results. + * + */ + public void clear() { + flush(); + getTemplate().clear(); + } + + /** + * Evicts the object from the session. This is essential for the + * implementation of unit tests where first an object is saved and is + * retrieved later. By removing the object from the session, Hibernate must + * retrieve the object again from the database. + * + * @param aObject + */ + protected void evict(Object aObject) { + getTemplate().evict(aObject); + } + + /** + * Gets the connection. + * + * @return Connection. + */ + public Connection getConnection() { + return DataSourceUtils.getConnection(getDataSource()); + } + + public void cleanDatabase() throws SQLException { + + if (!isDatabaseConfigured()) { + return; + } + + String[] tables = getTableNames(); + + try { + IDatabaseConnection connection = new DatabaseConnection( + getConnection()); + ITableFilter filter = new DatabaseSequenceFilter(connection, tables); + IDataSet dataset = new FilteredDataSet(filter, connection + .createDataSet(tables)); + + DatabaseOperation.DELETE_ALL.execute(connection, dataset); + } catch (DatabaseUnitException e) { + SQLException exc = new SQLException(e.getMessage()); + exc.initCause(e); + throw exc; + } + } + + /** + * @throws SQLException + */ + public String[] getTableNames() throws SQLException { + + List result = new ArrayList(); + LOG.debug("Getting database table names to clean (schema: '" + + SCHEMA_PATTERN + "'"); + + ResultSet tables = getConnection().getMetaData().getTables(null, + SCHEMA_PATTERN, "%", new String[] { "TABLE" }); + while (tables.next()) { + String table = tables.getString("TABLE_NAME"); + // Make sure we do not touch hibernate's specific + // infrastructure tables. + if (!table.toLowerCase().startsWith("hibernate")) { + result.add(table); + LOG.debug("Adding " + table + + " to list of tables to be cleaned."); + } + } + return (String[]) result.toArray(new String[0]); + } + + /** + * @return + * @throws SQLException + */ + public void emptyTables(List aTableList) throws SQLException { + Iterator liTable = aTableList.iterator(); + while (liTable.hasNext()) { + emptyTable((String) liTable.next()); + } + } + + /** + * @return + * @throws SQLException + */ + public void emptyTable(String aTable) throws SQLException { + executeSql("delete from " + aTable); + } + + /** + * @return + * @throws SQLException + */ + public void dropTable(String aTable) throws SQLException { + executeQuery("drop table " + aTable); + } + + /** + * Executes an SQL statement within a transaction. + * + * @param aSql + * SQL statement. + * @return Return code of the corresponding JDBC call. + */ + public int executeSql(final String aSql) { + return executeSql(aSql, new Object[0]); + } + + /** + * Executes an SQL statement within a transaction. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * SQL statement. + * @param aArg + * Argument of the sql statement. + * @return Return code of the corresponding JDBC call. + */ + public int executeSql(final String aSql, final Object aArg) { + return executeSql(aSql, new Object[] { aArg }); + } + + /** + * Executes an sql statement. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * SQL query to execute. + * @param aArgs + * Arguments. + * @return Number of rows updated. + */ + public int executeSql(final String aSql, final Object[] aArgs) { + Map results = executeTransaction(new TestTransactionCallback() { + public Map execute() throws Exception { + JdbcTemplate template = new JdbcTemplate(getDataSource()); + int result = template.update(aSql, aArgs); + + Map map = new TreeMap(); + map.put("result", new Integer(result)); + + return map; + } + }); + + return ((Integer) results.get("result")).intValue(); + } + + /** + * Executes a transaction with a result. + * + * @param aCallback + * Callback to do your transactional work. + * @return Result. + */ + public Object executeTransaction(TransactionCallback aCallback) { + TransactionTemplate lTemplate = new TransactionTemplate( + getTransactionManager()); + return lTemplate.execute(aCallback); + } + + /** + * Executes a transaction without a result. + * + * @param aCallback + * Callback to do your transactional work. . + */ + public void executeTransaction(TransactionCallbackWithoutResult aCallback) { + TransactionTemplate template = new TransactionTemplate( + getTransactionManager()); + template.execute(aCallback); + } + + /** + * Executes a transaction with a result, causing the testcase to fail if any + * type of exception is thrown. + * + * @param aCallback + * Code to be executed within the transaction. + * @return Result. + */ + public Map executeTransaction(final TestTransactionCallback aCallback) { + return (Map) executeTransaction(new TransactionCallback() { + public Object doInTransaction(TransactionStatus aArg) { + try { + return aCallback.execute(); + } catch (Exception e) { + // test case must fail. + e.printStackTrace(); + throw new RuntimeException(e); + } + } + }); + } + + /** + * Executes a transaction with a result, causing the testcase to fail if any + * type of exception is thrown. + * + * @param aCallback + * Code to be executed within the transaction. + */ + public void executeTransaction( + final TestTransactionCallbackWithoutResult aCallback) { + executeTransaction(new TransactionCallbackWithoutResult() { + public void doInTransactionWithoutResult(TransactionStatus aArg) { + try { + aCallback.execute(); + } catch (Exception e) { + // test case must fail. + throw new RuntimeException(e.getMessage(), e); + } + } + }); + } + + /** + * Executes an SQL query. + * + * @param aSql + * Query to execute. + * @return Result set. + */ + public ResultSet executeQuery(String aSql) { + return executeQuery(aSql, new Object[0]); + } + + /** + * Executes a query with a single argument. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * Query. + * @param aArg + * Argument. + * @return Result set. + */ + public ResultSet executeQuery(String aSql, Object aArg) { + return executeQuery(aSql, new Object[] { aArg }); + } + + /** + * Executes a query. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * Sql query. + * @param aArgs + * Arguments to the query. + * @return Result set. + */ + public ResultSet executeQuery(final String aSql, final Object[] aArgs) { + try { + Connection connection = getConnection(); + + PreparedStatement statement = connection.prepareStatement(aSql); + setPreparedParams(aArgs, statement); + + return statement.executeQuery(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + /** + * Sets the values of a prepared statement. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aArgs + * Arguments to the prepared statement. + * @param aStatement + * Prepared statement + * @throws SQLException + */ + private void setPreparedParams(final Object[] aArgs, + PreparedStatement aStatement) throws SQLException { + for (int i = 1; i <= aArgs.length; i++) { + setPreparedParam(i, aStatement, aArgs[i - 1]); + } + } + + /** + * Sets a prepared statement parameter. + * + * @param aIndex + * Index of the parameter. + * @param aStatement + * Prepared statement. + * @param aObject + * Value Must be of type Integer, Long, or String. + * @throws SQLException + */ + private void setPreparedParam(int aIndex, PreparedStatement aStatement, + Object aObject) throws SQLException { + if (aObject instanceof Integer) { + aStatement.setInt(aIndex, ((Integer) aObject).intValue()); + } else if (aObject instanceof Long) { + aStatement.setLong(aIndex, ((Integer) aObject).longValue()); + } else if (aObject instanceof String) { + aStatement.setString(aIndex, (String) aObject); + } else { + TestCase.fail("Unsupported object type for prepared statement: " + + aObject.getClass() + " value: " + aObject + + " statement: " + aStatement); + } + } + + private boolean isDatabaseConfigured() { + try { + getDataSource(); + } catch (NoSuchBeanDefinitionException e) { + return false; + } + return true; + } + + /** + * @return Returns the dataSource. + */ + public DataSource getDataSource() { + return _dataSource; + } + + /** + * @return + * @throws SQLException + */ + public int getTableSize(final String aTable) throws SQLException { + + ResultSet resultSet = executeQuery("select * from " + aTable); + int count = 0; + + while (resultSet.next()) { + count++; + } + return count; + } + + public int countResultSet(ResultSet aResultSet) throws SQLException { + int count = 0; + + while (aResultSet.next()) { + count++; + } + + return count; + } + +} diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.spring.properties b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.spring.properties new file mode 100644 index 00000000..747a0335 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.spring.properties @@ -0,0 +1 @@ +myproperty=Property Value diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.spring.xml b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.spring.xml new file mode 100644 index 00000000..238054b5 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.spring.xml @@ -0,0 +1,13 @@ + + + + + + Hello world! + + + + diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties.xml b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties.xml new file mode 100644 index 00000000..1ece7d14 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties.xml @@ -0,0 +1,13 @@ + + + + + + ${myproperty} + + + + diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties2.xml b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties2.xml new file mode 100644 index 00000000..1546261f --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithProperties2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithRequirements.xml b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithRequirements.xml new file mode 100644 index 00000000..a2f60d83 --- /dev/null +++ b/tags/wamblee-utils-0.2/system/spring/src/test/resources/test.org.wamblee.system.springWithRequirements.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/test/eclipselink/pom.xml b/tags/wamblee-utils-0.2/test/eclipselink/pom.xml new file mode 100644 index 00000000..141afcbe --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/pom.xml @@ -0,0 +1,56 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-test-eclipselink + jar + /test/eclipselink + http://wamblee.org + + + + org.wamblee + wamblee-test-enterprise + 0.2 + + + + org.wamblee + wamblee-test-enterprise + 0.2 + test-jar + + + + org.dbunit + dbunit + + + + javax.persistence + persistence-api + + + + org.eclipse.persistence + eclipselink + + + + + + + EclipseLink Repo + http://www.eclipse.org/downloads/download.php?r=1&nf=1&file=/rt/eclipselink/maven.repo + + + + + + diff --git a/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java b/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java new file mode 100644 index 00000000..856b0519 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkJpaCustomizer.java @@ -0,0 +1,30 @@ +package org.wamblee.support.persistence.eclipselink; + +import java.util.Map; + +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.wamblee.support.persistence.JpaCustomizer; +import org.wamblee.support.persistence.PersistenceUnitDescription; + +public class EclipselinkJpaCustomizer implements JpaCustomizer { + + public EclipselinkJpaCustomizer() { + // Empty + } + + @Override + public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + // Hack to make JNDI lookup of the datasource work with toplink + aJpaProperties.put("eclipselink.session.customizer", JndiSessionCustomizer.class + .getName()); + + // DDL generation for toplink + aJpaProperties.put("eclipselink.ddl-generation", "create-tables"); + } + + @Override + public ITableFilterSimple getJpaTables() { + return new EclipselinkTables(); + } + +} diff --git a/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java b/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java new file mode 100644 index 00000000..d4df0ddd --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/EclipselinkTables.java @@ -0,0 +1,20 @@ +package org.wamblee.support.persistence.eclipselink; + +import java.util.Arrays; +import java.util.List; + +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + +/** + * Toplink-specific tables. + */ +public class EclipselinkTables implements ITableFilterSimple { + + private static final List TABLES = Arrays.asList(new String[] { "SEQUENCE" } ); + + public boolean accept(String aTableName) throws DataSetException { + return TABLES.contains(aTableName); + } + +} diff --git a/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java b/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java new file mode 100644 index 00000000..9b856f05 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/src/main/java/org/wamblee/support/persistence/eclipselink/JndiSessionCustomizer.java @@ -0,0 +1,59 @@ +package org.wamblee.support.persistence.eclipselink; + +import javax.naming.Context; +import javax.naming.InitialContext; + +import org.eclipse.persistence.config.SessionCustomizer; +import org.eclipse.persistence.sessions.DatabaseLogin; +import org.eclipse.persistence.sessions.JNDIConnector; +import org.eclipse.persistence.sessions.Session; +import org.eclipse.persistence.sessions.server.ServerSession; + +/** + * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a + * JTA SE pu instead of a RESOURCE_LOCAL SE pu. + * + * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE + * environment together with our JNDI stub. + */ +public class JndiSessionCustomizer + implements SessionCustomizer { + + public JndiSessionCustomizer() { + // Empty. + } + + /** + * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP + */ + public void customize(Session session) throws Exception { + JNDIConnector connector = null; + Context context = null; + try { + context = new InitialContext(); + if(null != context) { + connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE + // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP + // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in + // the COMPOSITE_NAME_LOOKUP being set + // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set + connector.setLookupType(JNDIConnector.STRING_LOOKUP); + + // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe + JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector(); + writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP); + JNDIConnector readConnector = + (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector(); + readConnector.setLookupType(JNDIConnector.STRING_LOOKUP); + + System.out.println("JndiSessionCustomizer: configured " + connector.getName()); + } + else { + throw new Exception("JndiSessionCustomizer: Context is null"); + } + } + catch(Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/test/eclipselink/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer b/tags/wamblee-utils-0.2/test/eclipselink/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer new file mode 100644 index 00000000..35638de1 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer @@ -0,0 +1 @@ +org.wamblee.support.persistence.eclipselink.EclipselinkJpaCustomizer diff --git a/tags/wamblee-utils-0.2/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java b/tags/wamblee-utils-0.2/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java new file mode 100644 index 00000000..870e20a2 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/DatabaseUtilsTest.java @@ -0,0 +1,23 @@ +package org.wamblee.support.persistence.eclipselink; + +import static junit.framework.Assert.assertEquals; + +import javax.persistence.EntityManager; +import javax.sql.DataSource; + +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.DatabaseUtilsTestBase; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.PersistenceUnitDescription; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +public class DatabaseUtilsTest extends DatabaseUtilsTestBase { + // Empty, all tests inherited +} diff --git a/tags/wamblee-utils-0.2/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java b/tags/wamblee-utils-0.2/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java new file mode 100644 index 00000000..84c3fff5 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/eclipselink/src/test/java/org/wamblee/support/persistence/eclipselink/MyEntityExampleTest.java @@ -0,0 +1,29 @@ +package org.wamblee.support.persistence.eclipselink; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.dbunit.DataSourceDatabaseTester; +import org.dbunit.DatabaseTestCase; +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.JpaTester; +import org.wamblee.support.persistence.MyEntityExampleTestBase; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +import static junit.framework.Assert.*; + + +/** + * This class shows an example of how to test an entity using jpa. + */ +public class MyEntityExampleTest extends MyEntityExampleTestBase { + // Empty, all tests are inherited +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/pom.xml b/tags/wamblee-utils-0.2/test/enterprise/pom.xml new file mode 100644 index 00000000..9c61c482 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/pom.xml @@ -0,0 +1,70 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-test-enterprise + jar + /test/enterprise + http://wamblee.org + + + + org.wamblee + wamblee-support-general + 0.2 + test-jar + + + javax.transaction + transaction-api + + + junit + junit + compile + + + org.apache.derby + derby + + + mysql + mysql-connector-java + + + org.apache.derby + derbyclient + + + org.apache.derby + derbynet + + + commons-dbcp + commons-dbcp + + + javax.persistence + persistence-api + + + org.dbunit + dbunit + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-jdk14 + + + + diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContext.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContext.java new file mode 100644 index 00000000..a7e4c965 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContext.java @@ -0,0 +1,31 @@ +package org.wamblee.support.jndi; + +import java.util.HashMap; +import java.util.Map; + +import javax.naming.InitialContext; +import javax.naming.Name; +import javax.naming.NamingException; + +public class StubInitialContext extends InitialContext { + private Map bindings = new HashMap(); + + public StubInitialContext() throws NamingException { + super(true); + } + + @Override + public void bind(String name, Object obj) throws NamingException { + bindings.put(name, obj); + } + + @Override + public Object lookup(String name) throws NamingException { + return bindings.get(name); + } + + @Override + public Object lookup(Name name) throws NamingException { + return super.lookup(name.toString()); + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContextFactory.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContextFactory.java new file mode 100644 index 00000000..c7e4e2fd --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/jndi/StubInitialContextFactory.java @@ -0,0 +1,63 @@ +package org.wamblee.support.jndi; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +/** + * Test initial context factory used for testing software in a Java SE + * environnment that uses JNDI to retrieve objects. + * + * See {@link #bind(String, Object)} to resp. register the initial context. + * + * To bind objects in the JNDI tree simply use the standard JNDI api: + * InitialContext context = new InitialContext(); + * MyClass myObj = ...; + * context.bind("a/b", myObj); + * + */ +public class StubInitialContextFactory implements InitialContextFactory { + + private static Context context; + + private static void initialize() { + try { + context = new StubInitialContext(); + } catch (NamingException e) { // can't happen. + throw new RuntimeException(e); + } + } + + /** + * This method must be called to register this initial context factory as + * the default implementation for JNDI. + * + * @throws Exception + */ + public static void register() { + // sets up the InitialContextFactoryForTest as default factory. + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, + StubInitialContextFactory.class.getName()); + if (context == null) { + initialize(); + } + } + + /** + * Unregisters the initial context factory + */ + public static void unregister() { + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, ""); + context = null; + } + + public Context getInitialContext(Hashtable environment) + throws NamingException { + return context; + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabase.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabase.java new file mode 100644 index 00000000..59f3d776 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabase.java @@ -0,0 +1,78 @@ +package org.wamblee.support.persistence; + +import javax.sql.DataSource; + +import org.apache.commons.dbcp.ConnectionFactory; +import org.apache.commons.dbcp.DriverManagerConnectionFactory; +import org.apache.commons.dbcp.PoolableConnectionFactory; +import org.apache.commons.dbcp.PoolingDataSource; +import org.apache.commons.pool.impl.GenericObjectPool; + +public abstract class AbstractDatabase implements Database { + private static final int CONNECTION_POOL_SIZE = 16; + + private DataSource itsDataSource; + + private boolean started; + + protected AbstractDatabase() { + started = false; + } + + protected abstract void doStart(); + + protected abstract void doStop(); + + /** + * This method must be called from the start method. + */ + protected final void createDataSource() { + GenericObjectPool connectionPool = new GenericObjectPool(null); + connectionPool.setMaxActive(CONNECTION_POOL_SIZE); + ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(getJdbcUrl(), getUsername(), getPassword()); + // The following line must be kept in although it does not appear to be used, the constructor regsiters the + // constructed object at the connection pool. + PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true); + itsDataSource = new PoolingDataSource(connectionPool); + } + + + /// BELOW THIS LINE IS NOT OF INTEREST TO SUBCLASSES. + + public final DataSource start() { + if ( started ) { + throw new RuntimeException("Database already started"); + } + started = true; + doStart(); + return getDatasource(); + } + + public final void stop() { + if ( ! started ) { + return; // nothing to do. + } + started = false; + doStop(); + } + + private final DataSource getDatasource() { + if ( !started) { + throw new RuntimeException("Database is not started!"); + } + return itsDataSource; + } + + protected String getProperty(String aName) { + String value = System.getProperty(aName); + if ( value != null ) { + return value; + } + value = System.getenv(aName); + if ( value != null ) { + return value; + } + throw new RuntimeException("This class expects the '" + aName + "' property to be set"); + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabaseProvider.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabaseProvider.java new file mode 100644 index 00000000..6ed9d6cb --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/AbstractDatabaseProvider.java @@ -0,0 +1,18 @@ +package org.wamblee.support.persistence; + +import java.util.List; + +public abstract class AbstractDatabaseProvider implements DatabaseProvider { + + protected abstract List getCapabilities(); + + public final boolean supportsCapabilities(String[] aCapabilities) { + for (String capability: aCapabilities) { + if ( !getCapabilities().contains(capability)) { + return false; + } + } + return true; + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaCustomizer.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaCustomizer.java new file mode 100644 index 00000000..fc6ecc7c --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaCustomizer.java @@ -0,0 +1,33 @@ +package org.wamblee.support.persistence; + +import java.util.List; +import java.util.Map; + +import org.dbunit.dataset.filter.ITableFilterSimple; + +public class CompositeJpaCustomizer implements JpaCustomizer { + + private List _customizers; + private CompositeJpaTables _tables; + + public CompositeJpaCustomizer(List aCustomizers) { + _customizers = aCustomizers; + _tables = new CompositeJpaTables(); + for (JpaCustomizer customizer: _customizers) { + _tables.add(customizer.getJpaTables()); + } + } + + @Override + public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + for (JpaCustomizer customizer: _customizers) { + customizer.customize(aPersistenceUnit, aJpaProperties); + } + } + + @Override + public ITableFilterSimple getJpaTables() { + return _tables; + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaTables.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaTables.java new file mode 100644 index 00000000..7a7e8de6 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/CompositeJpaTables.java @@ -0,0 +1,31 @@ +package org.wamblee.support.persistence; + +import java.util.ArrayList; +import java.util.List; + +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + +public class CompositeJpaTables implements ITableFilterSimple { + + private List _tables; + + public CompositeJpaTables() { + _tables = new ArrayList(); + } + + public void add(ITableFilterSimple aFilter) { + _tables.add(aFilter); + } + + @Override + public boolean accept(String aTableName) throws DataSetException { + for (ITableFilterSimple filter: _tables) { + if (filter.accept(aTableName)) { + return true; + } + } + return false; + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/Database.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/Database.java new file mode 100755 index 00000000..f37474ea --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/Database.java @@ -0,0 +1,63 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support.persistence; + +import javax.sql.DataSource; + +/** + * Represents a database. + * + * @author Erik Brakkee + */ +public interface Database { + + /** + * Starts a database. This call should not block and return as soon as the + * database has been started. + */ + DataSource start(); + + /** + * Gets the Jdbc Url to connect to this database. + * + * @return Jdbc Url. + */ + String getJdbcUrl(); + + /** + * Gets the external Jdbc URL to connect to this database from other JVMs. + */ + String getExternalJdbcUrl(); + + /** + * Gets the username to connect to the database. + * + * @return username. + */ + String getUsername(); + + /** + * Gets the password to connect to the database. + * + * @return password. + */ + String getPassword(); + + /** + * Stops a database. + */ + void stop(); +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseBuilder.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseBuilder.java new file mode 100644 index 00000000..9c599a0a --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseBuilder.java @@ -0,0 +1,116 @@ +package org.wamblee.support.persistence; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.ServiceLoader; +import java.util.logging.Logger; + +/** + * DatabaseBuilder is used from unit test to obtain a reference to a database + * from unit test. This database is either an inmemory database or represents an + * external database. Purpose of this utility is to make test code independent of the + * particular database used and specifically to be able to run database tests without + * any configuration at all (using an inmemory database). + * + * The type of database to use can be overridden by specifying either a system + * property or an environment variable ({@link #DB_CAPABILITIES_PROP}) that + * contains the comma-separated capabilities of the database. Each database type + * provides its own capabilities (see {@link DatabaseProvider} implementations}. + * + * + * There are currently two database types available: + *
    + *
  • Derby: AN inmemory derby. Provided by {@link DerbyDatabaseProvider}. This is the default. + *
  • + *
  • External: An arbitrary external database configured using system properties or environment variables + * in the usual way using a JDBC URL, username, and password. + *
  • + *
+ * + * The DatabaseBuilder uses the {@link ServiceLoader} mechanism to find implementations + * of {@link DatabaseProvider} on the classpath. In the {@link #getDatabase(String...)} method a number of + * capabilities are passed. The database providers are then searched in (arbitrary) order and the first one that + * has all required capabilities is returned. + * + * {@link #getSupportedDatabases()} gives a list of all available databases. + */ +public class DatabaseBuilder { + + private static final Logger LOGGER = Logger.getLogger(DatabaseBuilder.class + .getName()); + + /** + * Environmment variable by which capabilities of the requested database can + * be defined + */ + private static final String DB_CAPABILITIES_PROP = "TEST_DB_CAPABILITIES"; + + private static ServiceLoader LOADER = null; + + private DatabaseBuilder() { + // Empty. + } + + private static String[] parseCapabilities(String aValue) { + return aValue.split(","); + } + + /** + * Gets the first database that has all required capabilities. + * @param aCapabilities Capabilities. + * @return Database to use. + */ + public static Database getDatabase(String... aCapabilities) { + if (aCapabilities.length == 0) { + LOGGER.info("Examining database capabilities"); + LOGGER.info(" Checking system property " + DB_CAPABILITIES_PROP); + String capabilities = System.getProperty(DB_CAPABILITIES_PROP); + if (capabilities != null) { + aCapabilities = parseCapabilities(capabilities); + } else { + LOGGER.info(" Checking environment variable " + + DB_CAPABILITIES_PROP); + capabilities = System.getenv(DB_CAPABILITIES_PROP); + if (capabilities != null) { + aCapabilities = parseCapabilities(capabilities); + } else { + LOGGER.info(" Using default capabilities"); + aCapabilities = new String[] { DatabaseProvider.CAPABILITY_IN_MEMORY }; + } + } + LOGGER.info("Using capabilities: " + aCapabilities); + } + synchronized (DatabaseBuilder.class) { + initLoader(); + for (DatabaseProvider db : LOADER) { + if (db.supportsCapabilities(aCapabilities)) { + return db.create(); + } + } + } + throw new RuntimeException( + "No database found that satisfies capabilities: " + + Arrays.asList(aCapabilities)); + } + + /** + * Gets a list of available databases. + * @return List of databases. + */ + public static List getSupportedDatabases() { + initLoader(); + List descriptions = new ArrayList(); + for (DatabaseProvider db : LOADER) { + descriptions.add(db.getDescription()); + } + return descriptions; + } + + private static void initLoader() { + if (LOADER == null) { + LOADER = ServiceLoader.load(DatabaseProvider.class); + } + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseDescription.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseDescription.java new file mode 100644 index 00000000..c31427bc --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseDescription.java @@ -0,0 +1,41 @@ +package org.wamblee.support.persistence; + +/** + * Description of a specific database. + */ +public class DatabaseDescription { + + private String[] itsCapabilities; + private String itsDatabase; + private String itsOther; + + /** + * Constructs the description. + * @param aCapabilities List of all capabilities. + * @param aDatabase Database. + * @param aOther Other information. + */ + public DatabaseDescription(String[] aCapabilities, String aDatabase, String aOther) { + itsCapabilities = aCapabilities; + itsDatabase = aDatabase; + itsOther = aOther; + } + + @Override + public String toString() { + return "\n Database " + itsDatabase + + "\n Capabilities: " + printCapabilities() + + "\n Other info: " + itsOther; + } + + private String printCapabilities() { + String res = ""; + for (int i = 0; i < itsCapabilities.length; i++) { + res += "" + itsCapabilities[i]; + if ( i < itsCapabilities.length -1 ) { + res += ", "; + } + } + return res; + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseProvider.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseProvider.java new file mode 100644 index 00000000..f6736aa1 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseProvider.java @@ -0,0 +1,42 @@ +package org.wamblee.support.persistence; + +/** + * Database provider. This database provider represents a particular type of + * database such as its capabilities and the ability to create an instance + * representing a running database. + * + * Since the {@link DatabaseBuilder} uses a first match algorithm and the order + * of databaseproviders is not guaranteed, it is recommended for each database + * provider to also provide a unique capability that no other database has. + */ +public interface DatabaseProvider { + + /** + * Capability that all databases that run inmemory have. + */ + String CAPABILITY_IN_MEMORY = "INMEMORY"; + + /** + * Capability that all databases that are external have. + */ + String CAPABILITY_EXTERNAL = "EXTERNAL"; + + /** + * Determines if the database has all capabilities that are requested. + * @param aCapabilities Capabilities it must ahve + * @return True if it has all capabilities. + */ + boolean supportsCapabilities(String[] aCapabilities); + + /** + * Gets the description for the database. + * @return Description. + */ + DatabaseDescription getDescription(); + + /** + * Creates a database instance that represents a running instance of that database. + * @return Database. + */ + Database create(); +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseStarter.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseStarter.java new file mode 100644 index 00000000..44294e35 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseStarter.java @@ -0,0 +1,106 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support.persistence; + + +/** + * This class is used for starting the database from ant. + */ +public class DatabaseStarter { + + /** + * Database class which encapsulates management of the database. + */ + private Class _databaseClass; + + /** + * Execution as a main program. Commandline + * + *
+     * 
+     *    DatabaseStarter <databaseClassName>
+     *  
+     * 
+ * + * where the database class name must be the name of a concrete subclass of + * {@link Database}. + * + * @param args + */ + public static void main( String[] args ) throws Exception { + String clazz = args[0]; + try { + new DatabaseStarter( Class.forName( clazz ) ).start( ); + } catch ( Exception e ) { + e.printStackTrace( ); + System.out + .println( "\nUsage: ant dbClass "); + } + } + + /** + * Constructs the database starter. + * + * @param aClassName + * Classname of the database class to use. + * @throws Exception + */ + public DatabaseStarter( Class aClass ) throws Exception { + if ( !Database.class.isAssignableFrom( aClass ) ) { + throw new IllegalArgumentException( "Class '" + + aClass.getName( ) + + "' is not a subclass of Database" ); + } + _databaseClass = aClass; + } + + /** + * Constructs a database starter with the derby database. + * + * @throws Exception + */ + public DatabaseStarter( ) throws Exception { + this( DerbyDatabase.class ); + } + + /** + * Starts the database. + * + * @throws Exception + */ + public void start( ) throws Exception { + Database lDatabase = (Database) _databaseClass.newInstance( ); + lDatabase.start( ); + System.out.println( "Database has been started. " ); + System.out.println( ); + System.out.println("======================================================="); + System.out.println( "Connection details:" ); + // System.out.println( " Driver class: " + // + lDatabase.getDriverClassName( ) ); + System.out.println( " JDBC URL: " + + lDatabase.getExternalJdbcUrl( ) ); + System.out.println( " username: '" + lDatabase.getUsername( ) + + "'" ); + System.out.println( " password: '" + lDatabase.getPassword( ) + + "'" ); + System.out.println( "Interrupt the program to stop the database." ); + System.out.println("======================================================="); + System.out.println("You must now populate the database with a schema. Use 'ant help' for information."); + for ( ;; ) { + Thread.sleep( 1000 ); + } + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseUtils.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseUtils.java new file mode 100644 index 00000000..312e38a0 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DatabaseUtils.java @@ -0,0 +1,389 @@ +package org.wamblee.support.persistence; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import javax.sql.DataSource; + +import junit.framework.TestCase; + +import org.dbunit.DataSourceDatabaseTester; +import org.dbunit.IDatabaseTester; +import org.dbunit.database.DatabaseConnection; +import org.dbunit.database.DatabaseSequenceFilter; +import org.dbunit.database.IDatabaseConnection; +import org.dbunit.dataset.FilteredDataSet; +import org.dbunit.dataset.IDataSet; +import org.dbunit.dataset.filter.ITableFilter; +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.dbunit.operation.DatabaseOperation; + +/** + * Database utilities is a simple support class for common tasks in working with + * databases. + */ +public class DatabaseUtils { + + public static interface TableSet { + boolean contains(String aTableName); + } + + public static interface JdbcUnitOfWork { + T execute(Connection aConnection) throws Exception; + } + + public static interface TableSetOperation { + void execute(String aTable) throws Exception; + } + + private static final Logger LOG = Logger.getLogger(DatabaseUtils.class + .getName()); + + /** + * Schema pattern. + */ + private static final String SCHEMA_PATTERN = "%"; + private DataSource dataSource; + private ITableFilterSimple tables; + + + public DatabaseUtils(DataSource aDataSource, ITableFilterSimple aTables) { + dataSource = aDataSource; + tables = aTables; + } + + public IDatabaseTester createDbTester() throws Exception { + return createDbTester(getTableNames(tables)); + } + + public IDatabaseTester createDbTester(String[] aTables) throws Exception { + IDatabaseTester dbtester = new DataSourceDatabaseTester(dataSource); + dbtester.setDataSet(dbtester.getConnection().createDataSet(aTables)); + return dbtester; + } + + public void cleanDatabase() throws Exception { + cleanDatabase(tables); + } + + public void executeOnTables(ITableFilterSimple aTables, + final TableSetOperation aOperation) throws Exception { + final String[] tables = getTableNames(aTables); + executeInTransaction(new JdbcUnitOfWork() { + public Void execute(Connection aConnection) throws Exception { + for (int i = tables.length - 1; i >= 0; i--) { + aOperation.execute(tables[i]); + } + return null; + } + }); + for (String table : tables) { + + } + } + + public void cleanDatabase(ITableFilterSimple aSelection) throws Exception { + + final String[] tables = getTableNames(aSelection); + executeInTransaction(new JdbcUnitOfWork() { + + public Void execute(Connection aConnection) throws Exception { + IDatabaseConnection connection = new DatabaseConnection( + aConnection); + ITableFilter filter = new DatabaseSequenceFilter(connection, + tables); + IDataSet dataset = new FilteredDataSet(filter, connection + .createDataSet(tables)); + DatabaseOperation.DELETE_ALL.execute(connection, dataset); + return null; + } + }); + + } + + public T executeInTransaction(JdbcUnitOfWork aCallback) + throws Exception { + Connection connection = dataSource.getConnection(); + try { + T value = aCallback.execute(connection); + connection.commit(); + return value; + } finally { + connection.close(); + } + } + + public String[] getTableNames() throws Exception { + return getTableNames(tables); + } + + /** + * @throws SQLException + */ + public String[] getTableNames(ITableFilterSimple aSelection) + throws Exception { + + List result = new ArrayList(); + LOG.fine("Getting database table names to clean (schema: '" + + SCHEMA_PATTERN + "'"); + + ResultSet tables = dataSource.getConnection().getMetaData().getTables( + null, SCHEMA_PATTERN, "%", new String[] { "TABLE" }); + while (tables.next()) { + String table = tables.getString("TABLE_NAME"); + if (aSelection.accept(table)) { + result.add(table); + } + } + return (String[]) result.toArray(new String[0]); + } + + public void emptyTables() throws Exception { + executeOnTables(tables, new TableSetOperation() { + public void execute(String aTable) throws Exception { + emptyTable(aTable); + } + }); + } + + /** + * @return + * @throws SQLException + */ + public void emptyTables(final ITableFilterSimple aSelection) + throws Exception { + executeOnTables(aSelection, new TableSetOperation() { + public void execute(String aTable) throws Exception { + emptyTable(aTable); + } + }); + } + + /** + * @return + * @throws SQLException + */ + public void emptyTable(String aTable) throws Exception { + executeSql("delete from " + aTable); + } + + public void dropTables() throws Exception { + executeOnTables(tables, new TableSetOperation() { + + public void execute(String aTable) throws Exception { + dropTable(aTable); + } + }); + } + + + public void dropTables(ITableFilterSimple aTables) throws Exception { + executeOnTables(aTables, new TableSetOperation() { + + public void execute(String aTable) throws Exception { + dropTable(aTable); + } + }); + } + + /** + * @return + * @throws SQLException + */ + public void dropTable(final String aTable) throws Exception { + executeInTransaction(new JdbcUnitOfWork() { + public Void execute(Connection aConnection) throws Exception { + executeUpdate(aConnection, "drop table " + aTable); + return null; + } + }); + + } + + /** + * Executes an SQL statement within a transaction. + * + * @param aSql + * SQL statement. + * @return Return code of the corresponding JDBC call. + */ + public int executeSql(final String aSql) throws Exception { + return executeSql(aSql, new Object[0]); + } + + /** + * Executes an SQL statement within a transaction. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * SQL statement. + * @param aArg + * Argument of the sql statement. + * @return Return code of the corresponding JDBC call. + */ + public int executeSql(final String aSql, final Object aArg) + throws Exception { + return executeSql(aSql, new Object[] { aArg }); + } + + /** + * Executes an sql statement. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * SQL query to execute. + * @param aArgs + * Arguments. + * @return Number of rows updated. + */ + public int executeSql(final String aSql, final Object[] aArgs) + throws Exception { + return executeInTransaction(new JdbcUnitOfWork() { + public Integer execute(Connection aConnection) throws Exception { + PreparedStatement stmt = aConnection.prepareStatement(aSql); + setPreparedParams(aArgs, stmt); + return stmt.executeUpdate(); + } + }); + } + + /** + * Executes an SQL query. + * + * @param aSql + * Query to execute. + * @return Result set. + */ + public ResultSet executeQuery(Connection aConnection, String aSql) { + return executeQuery(aConnection, aSql, new Object[0]); + } + + /** + * Executes a query with a single argument. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * Query. + * @param aArg + * Argument. + * @return Result set. + */ + public ResultSet executeQuery(Connection aConnection, String aSql, + Object aArg) { + return executeQuery(aConnection, aSql, new Object[] { aArg }); + } + + /** + * Executes a query. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aSql + * Sql query. + * @param aArgs + * Arguments to the query. + * @return Result set. + */ + public ResultSet executeQuery(Connection aConnection, final String aSql, + final Object[] aArgs) { + try { + PreparedStatement statement = aConnection.prepareStatement(aSql); + setPreparedParams(aArgs, statement); + + return statement.executeQuery(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + public int executeUpdate(Connection aConnection, final String aSql, + final Object... aArgs) { + try { + PreparedStatement statement = aConnection.prepareStatement(aSql); + setPreparedParams(aArgs, statement); + + return statement.executeUpdate(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + /** + * Sets the values of a prepared statement. See + * {@link #setPreparedParam(int, PreparedStatement, Object)}for details on + * supported argument types. + * + * @param aArgs + * Arguments to the prepared statement. + * @param aStatement + * Prepared statement + * @throws SQLException + */ + private void setPreparedParams(final Object[] aArgs, + PreparedStatement aStatement) throws SQLException { + for (int i = 1; i <= aArgs.length; i++) { + setPreparedParam(i, aStatement, aArgs[i - 1]); + } + } + + /** + * Sets a prepared statement parameter. + * + * @param aIndex + * Index of the parameter. + * @param aStatement + * Prepared statement. + * @param aObject + * Value Must be of type Integer, Long, or String. + * @throws SQLException + */ + private void setPreparedParam(int aIndex, PreparedStatement aStatement, + Object aObject) throws SQLException { + if (aObject instanceof Integer) { + aStatement.setInt(aIndex, ((Integer) aObject).intValue()); + } else if (aObject instanceof Long) { + aStatement.setLong(aIndex, ((Integer) aObject).longValue()); + } else if (aObject instanceof String) { + aStatement.setString(aIndex, (String) aObject); + } else { + TestCase.fail("Unsupported object type for prepared statement: " + + aObject.getClass() + " value: " + aObject + + " statement: " + aStatement); + } + } + + /** + * @return + * @throws SQLException + */ + public int getTableSize(final String aTable) throws Exception { + return executeInTransaction(new JdbcUnitOfWork() { + public Integer execute(Connection aConnection) throws Exception { + ResultSet resultSet = executeQuery(aConnection, + "select count(*) from " + aTable); + resultSet.next(); + return resultSet.getInt(1); + } + }); + + } + + public int countResultSet(ResultSet aResultSet) throws SQLException { + int count = 0; + + while (aResultSet.next()) { + count++; + } + + return count; + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabase.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabase.java new file mode 100755 index 00000000..646931c5 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabase.java @@ -0,0 +1,314 @@ +/* + * Copyright 2005 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.wamblee.support.persistence; + +import java.io.File; +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + +import junit.framework.TestCase; + +import org.apache.derby.drda.NetworkServerControl; +import org.wamblee.io.FileSystemUtils; + +/** + * Derby database setup. The external JDBC url used to connect to a running + * instance is + * + *
+ *     jdbc:derby:net://localhost:1527/testdb
+ * 
+ * + * and the driver class is + * + *
+ * com.ibm.db2.jcc.DB2Driver
+ * 
+ * + * The following jars will have to be used db2jcc.jar and + * db2jcc_license_c.jar. + */ +public class DerbyDatabase extends AbstractDatabase { + + /** + * Logger. + */ + private static final Logger LOGGER = Logger.getLogger(DerbyDatabase.class + .getName()); + + /** + * Database user name. + */ + private static final String USERNAME = "sa"; + + /** + * Database password. + */ + private static final String PASSWORD = "123"; + /** + * Poll interval for the checking the server status. + */ + private static final int POLL_INTERVAL = 100; + + /** + * Maximum time to wait until the server has started or stopped. + */ + private static final int MAX_WAIT_TIME = 10000; + + /** + * Database name to use. + */ + private static final String DATABASE_NAME = "testdb"; + + /** + * Path on the file system where derby files are stored. + */ + private static final String DATABASE_PATH = "target/db/persistence/derby"; + + /** + * Derby property required to set the file system path + * {@link #DATABASE_PATH}. + */ + private static final String SYSTEM_PATH_PROPERTY = "derby.system.home"; + + + private boolean inmemory; + + + /** + * Constructs derby database class to allow creation of derby database + * instances. + */ + public DerbyDatabase() { + inmemory = true; + } + + public DerbyDatabase(boolean aInMemoryFlag) { + inmemory = aInMemoryFlag; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.persistence.Database#start() + */ + public void doStart() { + try { + // just in case a previous run was killed without the + // cleanup + cleanPersistentStorage(); + + if (!inmemory) { + // set database path. + Properties lProperties = System.getProperties(); + lProperties.put(SYSTEM_PATH_PROPERTY, DATABASE_PATH); + } + + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + + runDatabase(); + + waitUntilStartedOrStopped(true); + + // Force creation of the database. + Connection lConnection = createConnection(); + lConnection.close(); + + LOGGER.info("Database started: \n URL = " + getExternalJdbcUrl() + "\n user = " + getUsername() + "\n password = " + + getPassword()); + + createDataSource(); + + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + if (isStarted()) { + LOGGER.warning("Shutting down db"); + DerbyDatabase.this.stop(); + } + } + }); + } catch (Exception e) { + throw new RuntimeException("Problem starting database", e); + } + } + + /** + * Waits until the database server has started or stopped. + * + * @param aStarted + * If true, waits until the server is up, if false, waits until + * the server is down. + * @throws InterruptedException + */ + private void waitUntilStartedOrStopped(boolean aStarted) + throws InterruptedException { + long lWaited = 0; + + while (aStarted != isStarted()) { + Thread.sleep(POLL_INTERVAL); + lWaited += POLL_INTERVAL; + + if (lWaited > MAX_WAIT_TIME) { + throw new RuntimeException( + "Derby database did not start within " + MAX_WAIT_TIME + + "ms"); + } + } + } + + /** + * Checks if the database server has started or not. + * + * @return True if started, false otherwise. + */ + private boolean isStarted() { + try { + getControl().ping(); + + return true; + } catch (Exception e) { + return false; + } + } + + /** + * Gets the controller for the database server. + * + * @return Controller. + * @throws Exception + */ + private NetworkServerControl getControl() throws Exception { + return new NetworkServerControl(); + } + + /** + * Runs the database. + * + */ + private void runDatabase() { + try { + getControl().start(new PrintWriter(System.out)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.persistence.Database#getJdbcUrl() + */ + public String getJdbcUrl() { + return getBaseJdbcUrl() + + ";create=true;retrieveMessagesFromServerOnGetMessage=true;"; + } + + private String getBaseJdbcUrl() { + return (inmemory ? "jdbc:derby:memory:": "jdbc:derby:") + DATABASE_NAME; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.persistence.Database#getExternalJdbcUrl() + */ + public String getExternalJdbcUrl() { + return "jdbc:derby://localhost:1527/" + (inmemory ? "memory:" : "") + DATABASE_NAME; + } + + /** + * Shuts down the derby database and cleans up all created files. + * + */ + private void shutdownDerby() { + try { + DriverManager.getConnection("jdbc:derby:;shutdown=true"); + throw new RuntimeException("Derby did not shutdown, " + + " should always throw exception at shutdown"); + } catch (Exception e) { + LOGGER.info("Derby has been shut down."); + } + } + + /** + * Gets the user name. + */ + public String getUsername() { + return USERNAME; + } + + /** + * Gets the password. + * + * @return + */ + public String getPassword() { + return PASSWORD; + } + + /* + * (non-Javadoc) + * + * @see org.wamblee.persistence.Database#createConnection() + */ + public Connection createConnection() throws SQLException { + Connection c = DriverManager.getConnection(getJdbcUrl(), getUsername(), + getPassword()); + + return c; + } + + + /** + * Stops the derby database and cleans up all derby files. + */ + public void doStop() { + try { + // shutdown network server. + getControl().shutdown(); + waitUntilStartedOrStopped(false); + + // shutdown inmemory access. + shutdownDerby(); + cleanPersistentStorage(); + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Problem stopping database", e); + } + } + + /** + * Cleans up persistent storage of Derby. + */ + private void cleanPersistentStorage() { + File lFile = new File(DATABASE_PATH); + + if (lFile.isFile()) { + TestCase.fail("A regular file by the name " + DATABASE_PATH + + " exists, clean this up first"); + } + + if (!lFile.isDirectory()) { + return; // no-op already cleanup up. + } + FileSystemUtils.deleteDirRecursively(DATABASE_PATH); + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java new file mode 100644 index 00000000..088202c3 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/DerbyDatabaseProvider.java @@ -0,0 +1,32 @@ +package org.wamblee.support.persistence; + +import java.util.Arrays; +import java.util.List; + +public class DerbyDatabaseProvider extends AbstractDatabaseProvider { + + /** + * Capabilities of this type of database. + */ + public static final List CAPABILIITIES = + Arrays.asList(DatabaseProvider.CAPABILITY_IN_MEMORY, "DERBY"); + + + public DerbyDatabaseProvider() { + // Empty + } + + public Database create() { + return new DerbyDatabase(); + } + + public DatabaseDescription getDescription() { + return new DatabaseDescription(CAPABILIITIES.toArray(new String[0]), + "Derby", "In-memory, volatile, set breakpoint to debug"); + } + + @Override + protected List getCapabilities() { + return CAPABILIITIES; + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabase.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabase.java new file mode 100644 index 00000000..2533df42 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabase.java @@ -0,0 +1,82 @@ +package org.wamblee.support.persistence; + +import java.util.Arrays; +import java.util.List; +import java.util.logging.Logger; + +import javax.sql.DataSource; + +import org.apache.commons.dbcp.ConnectionFactory; +import org.apache.commons.dbcp.DriverManagerConnectionFactory; +import org.apache.commons.dbcp.PoolableConnectionFactory; +import org.apache.commons.dbcp.PoolingDataSource; +import org.apache.commons.pool.impl.GenericObjectPool; + +/** + * Database that encapsulates connection to an external database. + * Database connection details can be configured through system properties + * and environment variables, see {@link #DB_URL_PROP}, {@link #DB_USER_PROP}, and + * {@link #DB_PASSWORD_PROP|. + * + * This class assumes modern database drivers that work together with java.util.ServiceLoader + * so that explicitly doing a Class.forName() is not necessary to load the database driver. + */ +public class ExternalDatabase extends AbstractDatabase { + + private static final Logger LOGGER = Logger.getLogger(ExternalDatabase.class.getName()); + + /** + * System property/environment variable that defines the database URL. + */ + public static final String DB_URL_PROP = "TEST_DB_URL"; + + /** + * System property/environment variable that defines the database user. + */ + public static final String DB_USER_PROP = "TEST_DB_USER"; + + /** + * System property/environment variable that defines the database password. + */ + public static final String DB_PASSWORD_PROP = "TEST_DB_PASSWORD"; + + + private String itsUrl; + private String itsUser; + private String itsPassword; + + private DataSource itsDataSource; + + public ExternalDatabase() { + // Empty + } + + public String getExternalJdbcUrl() { + return itsUrl; + } + + public String getJdbcUrl() { + return itsUrl; + } + + public String getPassword() { + return itsPassword; + } + + public String getUsername() { + return itsUser; + } + + public void doStart() { + itsUrl = getProperty(DB_URL_PROP); + itsUser = getProperty(DB_USER_PROP); + itsPassword = getProperty(DB_PASSWORD_PROP); + + createDataSource(); + } + + public void doStop() { + // Empty. + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabaseProvider.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabaseProvider.java new file mode 100644 index 00000000..871be11a --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/ExternalDatabaseProvider.java @@ -0,0 +1,35 @@ +package org.wamblee.support.persistence; + +import java.util.Arrays; +import java.util.List; + +public class ExternalDatabaseProvider extends AbstractDatabaseProvider { + + /** + * Capabilities of this type of database. + */ + public static final List CAPABILIITIES = Arrays + .asList(CAPABILITY_EXTERNAL); + + @Override + protected List getCapabilities() { + return CAPABILIITIES; + } + + public Database create() { + return new ExternalDatabase(); + } + + public DatabaseDescription getDescription() { + return new DatabaseDescription( + CAPABILIITIES.toArray(new String[0]), + "External Database", + "Any database as described by the JDBC URL: requires system properties or environment variables: " + + ExternalDatabase.DB_URL_PROP + + ", " + + ExternalDatabase.DB_USER_PROP + + ", and " + + ExternalDatabase.DB_PASSWORD_PROP); + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaBuilder.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaBuilder.java new file mode 100644 index 00000000..8b6e3399 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaBuilder.java @@ -0,0 +1,136 @@ +package org.wamblee.support.persistence; + +import java.util.Map; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.wamblee.support.jndi.StubInitialContextFactory; + + +/** + * Utility for building an appropriately configured EntityManagerFactory. The + * idea is that a persistence.xml is used unchanged from the production version. + * This utility will then add the additional properties required for execution + * in a standalone environment. + * + * The other purpose is to to shield dependencies of the test code on a + * particular JPA provider. + */ +public class JpaBuilder { + + private static final Logger LOGGER = Logger.getLogger(JpaBuilder.class + .getName()); + + /** + * Callback interface to execute some JPA code within a transaction with the + * entitymanager to use provided as input. + */ + public static interface JpaUnitOfWork { + /** + * Executes the unit of work. A transaction has been started. + * @param em Entity manager. + * @return Result of the execute method. If you don't want to return anything use + * Void for the return type and return null from the implementation. + */ + T execute(EntityManager em); + } + + private PersistenceUnitDescription persistenceUnit; + private DataSource dataSource; + private EntityManagerFactory factory; + + /** + * Constructs the builder. + * + * @param aDataSource + * Datasource of database. + * @param aPersistenceUnit + * Persistence unit. + */ + public JpaBuilder(DataSource aDataSource, + PersistenceUnitDescription aPersistenceUnit) { + persistenceUnit = aPersistenceUnit; + dataSource = aDataSource; + StubInitialContextFactory.register(); + } + + /** + * Starts the builder, which in particular, mocks JNDI, binds the datasource + * the JNDI where the persistence unit expects it, creates the entity + * manager factory, and forces creation of the database schema. + */ + public void start() throws Exception { + try { + InitialContext ctx = new InitialContext(); + ctx.bind(persistenceUnit.getJndiName(), dataSource); + } catch (NamingException e) { + throw new RuntimeException("JNDI problem", e); + } + factory = createFactory(); + execute(new JpaUnitOfWork() { + public Void execute(EntityManager em) { + // Empty, just to trigger database schema creation. + return null; + } + }); + } + + /** + * Stops the entity manager factory and disables JNDI mocking. + */ + public void stop() { + StubInitialContextFactory.unregister(); + factory.close(); + } + + /** + * Creates a new entity manager factory. Typically not used by test code. + * @return Entity manager factory. + */ + public EntityManagerFactory createFactory() { + Map jpaProps = new TreeMap(); + + JpaCustomizerBuilder.getCustomizer().customize(persistenceUnit, jpaProps); + + //jpaProps.put("javax.persistence.provider", HibernatePersistence.class.getName()); + EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnit + .getUnitName(), jpaProps); + + LOGGER.info("Using " + factory.getClass()); + return factory; + } + + /** + * Executes a unit of work. This creates an entitymanager and runs the + * {@link JpaUnitOfWork#execute(EntityManager)} within a transaction, passing + * it the entity manager. Use of this method saves a lot of typing for applications. + * + * @param aWork Work to execute. + * @return The return value of the execute method of the unit of work. + */ + public T execute(JpaUnitOfWork aWork) throws Exception { + EntityManager em = factory.createEntityManager(); + EntityTransaction transaction = em.getTransaction(); + transaction.begin(); + try { + T value = aWork.execute(em); + transaction.commit(); + return value; + } catch (Exception e) { + LOGGER.log(Level.WARNING, "Exception occured", e); + transaction.rollback(); + throw e; + } finally { + em.close(); + } + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizer.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizer.java new file mode 100644 index 00000000..79303012 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizer.java @@ -0,0 +1,22 @@ +package org.wamblee.support.persistence; + +import java.util.Map; +import java.util.ServiceLoader; + +import org.dbunit.dataset.filter.ITableFilterSimple; + +/** + * JPA customizer is used to customize properties for a given JPA implementation. + * + * Implementations of JpaCustomizer are found using {@link ServiceLoader}. In case + * of testing with a specific JPA provider, the customizer library for that JPA provider + * must be on the classpath as well. + * + * @author Erik Brakkee + */ +public interface JpaCustomizer { + + void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties); + + ITableFilterSimple getJpaTables(); +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizerBuilder.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizerBuilder.java new file mode 100644 index 00000000..a824bf6f --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaCustomizerBuilder.java @@ -0,0 +1,20 @@ +package org.wamblee.support.persistence; + +import java.util.ArrayList; +import java.util.List; +import java.util.ServiceLoader; + +public class JpaCustomizerBuilder { + + private static final ServiceLoader CUSTOMIZERS = + ServiceLoader.load(JpaCustomizer.class); + + + public static JpaCustomizer getCustomizer() { + List customizers = new ArrayList(); + for (JpaCustomizer customizer: CUSTOMIZERS) { + customizers.add(customizer); + } + return new CompositeJpaCustomizer(customizers); + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaTester.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaTester.java new file mode 100644 index 00000000..a6a512f1 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/JpaTester.java @@ -0,0 +1,113 @@ +package org.wamblee.support.persistence; + +import javax.sql.DataSource; + +import org.dbunit.IDatabaseTester; + +/** + * This class is the entry point for JPA tests. Test code should construct a JpaTester in the + * @Before method and call {@link #start()} on it in that method. Also, test code should + * call {@link #stop()} on it in the @After method. + * + * This class is constructed with a description of the persistence unit to be tested. The principle is that + * an existing persistence.xml can be tested without change in unit test code. + * + * It then takes care of the following: + *
    + *
  • Creating an inmemory database for testing (default) or connecting to an external database. + * See {@link DatabaseBuilder} for more information on how a databse is obtained. + *
  • + *
  • Drop all database tables that are related to the persistence unit under test, including JPA provider + * specific tables. + *
  • + *
  • Creating a datasource for the database and make the datasource available through JNDI. + *
  • + *
  • Creating the entity manager factory for JPA and configuring it in such a way that schema creation + * happens. (Typically, schema creation will be disabled in the persistence.xml but this utility enables it + * for unit test). + *
  • + *
  • Creating a DBUnit database tester which is appropriately configured for the persistence unit under test. + *
  • + *
+ * + * The main entry point for all this functionality is the {@link PersistenceUnitDescription} which describes the + * persistence unit and must be provided at construction of the JpaTester + * + * NOTE: Persistence XML files should be explicitly configured with the classes that are part of the persistence unit + * since scanning of classes does not work correctly in a unit test environment. This is currently the only limitation. + */ +public class JpaTester { + + private PersistenceUnitDescription persistenceUnit; + private Database db; + private DataSource dataSource; + private DatabaseUtils dbUtils; + private JpaBuilder jpaBuilder; + private IDatabaseTester dbTester; + + /** + * Constructs the tester. + * @param aPersistenceUnit Persistence unit under test. + */ + public JpaTester(PersistenceUnitDescription aPersistenceUnit) { + persistenceUnit = aPersistenceUnit; + } + + /** + * Starts the tester. This must be called prior to running the test. + * @throws Exception + */ + public void start() throws Exception { + db = DatabaseBuilder.getDatabase(); + dataSource = db.start(); + + dbUtils = new DatabaseUtils(dataSource, persistenceUnit.getTables()); + dbUtils.dropTables(); + dbUtils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables()); + + jpaBuilder = new JpaBuilder(dataSource, persistenceUnit); + jpaBuilder.start(); + + // db tester should be created after Jpa builder because jpa builder + // creates the + // tables that the tester looks at when it is initialized. + dbTester = dbUtils.createDbTester(); + } + + /** + * Stops the tester. This must be called after the test. + */ + public void stop() { + if (jpaBuilder != null) { + jpaBuilder.stop(); + } + if (db != null) { + db.stop(); + } + } + + public Database getDb() { + return db; + } + + public DataSource getDataSource() { + return dataSource; + } + + public IDatabaseTester getDbTester() { + return dbTester; + } + + public DatabaseUtils getDbUtils() { + return dbUtils; + } + + public JpaBuilder getJpaBuilder() { + return jpaBuilder; + } + + public PersistenceUnitDescription getPersistenceUnit() { + return persistenceUnit; + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/PersistenceUnitDescription.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/PersistenceUnitDescription.java new file mode 100644 index 00000000..a2499b47 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/PersistenceUnitDescription.java @@ -0,0 +1,28 @@ +package org.wamblee.support.persistence; + +import org.dbunit.dataset.filter.ITableFilterSimple; + +public class PersistenceUnitDescription { + + private String jndiName; + private String unitName; + private ITableFilterSimple tables; + + public PersistenceUnitDescription(String aJndiName, String aUnitName, ITableFilterSimple aTables) { + jndiName = aJndiName; + unitName = aUnitName; + tables = aTables; + } + + public String getJndiName() { + return jndiName; + } + + public String getUnitName() { + return unitName; + } + + public ITableFilterSimple getTables() { + return tables; + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/package-info.java b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/package-info.java new file mode 100644 index 00000000..1bd7050c --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/java/org/wamblee/support/persistence/package-info.java @@ -0,0 +1,23 @@ +/** + * This package provide a number of utilities for database testing and in particular with + * JPA. + * + * The following utilities are available: + *
    + *
  • {@link JpaTester}: The main entry point for all JPA tests. + *
  • + *
  • {@link JpaBuilder}: A utility constructed by JpaTester that provides a callback based + * style of working with transaction-scoped entity managers. + *
  • + *
  • {@link DatabaseUtils}: A utility constructed by JpaTester for working with databases in general. Test code will not use this + * utility often. + *
  • + *
  • {@link org.dbunit.IDatabaseTester}: A DB unit database tester. The test code can use this database tester. + * It is also created by JpaTester + *
  • + *
  • {@link DatabaseBuilder}: A utility by which test code can transparently create an inmemory database or + * connect to an external database. This is also used by JpaTester + *
  • + *
+ */ +package org.wamblee.support.persistence; diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/main/resources/META-INF/services/org.wamblee.support.persistence.DatabaseProvider b/tags/wamblee-utils-0.2/test/enterprise/src/main/resources/META-INF/services/org.wamblee.support.persistence.DatabaseProvider new file mode 100644 index 00000000..62979fb3 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/main/resources/META-INF/services/org.wamblee.support.persistence.DatabaseProvider @@ -0,0 +1,2 @@ +org.wamblee.support.persistence.DerbyDatabaseProvider +org.wamblee.support.persistence.ExternalDatabaseProvider diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/jndi/StubInitiaContextFactoryTest.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/jndi/StubInitiaContextFactoryTest.java new file mode 100644 index 00000000..6016e2b3 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/jndi/StubInitiaContextFactoryTest.java @@ -0,0 +1,41 @@ +package org.wamblee.support.jndi; + +import static junit.framework.Assert.assertEquals; + +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.jndi.StubInitialContextFactory; + +public class StubInitiaContextFactoryTest { + + @Before + @After + public void setUp() { + StubInitialContextFactory.unregister(); + } + + + @Test(expected = NamingException.class) + public void testLookupNotRegistered() throws Exception { + InitialContext ctx = new InitialContext(); + ctx.bind("a/b", "hallo"); + } + + @Test + public void testLookup() throws Exception { + StubInitialContextFactory.register(); + + InitialContext ctx = new InitialContext(); + ctx.bind("a/b", "hallo"); + + ctx = new InitialContext(); + Object obj = ctx.lookup("a/b"); + + assertEquals("hallo", obj); + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseBuilderTest.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseBuilderTest.java new file mode 100644 index 00000000..51364876 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseBuilderTest.java @@ -0,0 +1,16 @@ +package org.wamblee.support.persistence; + +import org.junit.Test; +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.support.persistence.DatabaseDescription; + +public class DatabaseBuilderTest { + + + @Test + public void testListAvailableDatabases() { + for (DatabaseDescription description: DatabaseBuilder.getSupportedDatabases()) { + System.out.println(description); + } + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseUtilsTestBase.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseUtilsTestBase.java new file mode 100644 index 00000000..e55f1341 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DatabaseUtilsTestBase.java @@ -0,0 +1,89 @@ +package org.wamblee.support.persistence; + +import static junit.framework.Assert.assertEquals; + +import javax.persistence.EntityManager; +import javax.sql.DataSource; + +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.PersistenceUnitDescription; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +public class DatabaseUtilsTestBase { + private Database db; + private DataSource dataSource; + private PersistenceUnitDescription persistenceUnit; + private JpaBuilder builder; + private DatabaseUtils dbutils; + private IDatabaseTester dbtester; + + @Before + public void setUp() throws Exception { + db = DatabaseBuilder.getDatabase(); + dataSource = db.start(); + + persistenceUnit = new MyPersistenceUnit(); + + dbutils = new DatabaseUtils(dataSource, persistenceUnit.getTables()); + dbutils.dropTables(); + dbutils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables()); + + builder = new JpaBuilder(dataSource, persistenceUnit); + builder.start(); + + dbtester = dbutils.createDbTester(); + } + + @After + public void tearDown() { + builder.stop(); + db.stop(); + } + + @Test + public void testTablesCorrect() throws Exception { + String[] tables = dbutils.getTableNames(); + assertEquals(1, tables.length); + assertEquals("XYZ_MYENTITY", tables[0]); + } + + @Test + public void testDeleteTables() throws Exception { + String[] tables = dbutils.getTableNames(); + assertEquals(1, tables.length); + assertEquals("XYZ_MYENTITY", tables[0]); + + // Put some data in the database. + builder.execute(new JpaUnitOfWork() { + public Void execute(EntityManager em) { + MyEntity entity = new MyEntity("a", "b"); + em.persist(entity); + return null; + } + }); + + // Verify one row is written (using Db unit) + ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY"); + assertEquals(1, table.getRowCount()); + + // Clean the database + dbutils.cleanDatabase(); + table = dbtester.getDataSet().getTable("XYZ_MYENTITY"); + assertEquals(0, table.getRowCount()); + + // Now drop the database + dbutils.dropTables(); + dbutils.dropTables(JpaCustomizerBuilder.getCustomizer().getJpaTables()); + tables = dbutils.getTableNames(); + assertEquals(0, tables.length); + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DerbyDatabaseTest.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DerbyDatabaseTest.java new file mode 100644 index 00000000..ffc17aea --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/DerbyDatabaseTest.java @@ -0,0 +1,47 @@ +package org.wamblee.support.persistence; + +import java.sql.Connection; + +import javax.sql.DataSource; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DatabaseBuilder; + + +public class DerbyDatabaseTest { + + private Database db; + private DataSource ds; + + @Before + public void setUp() { + db = DatabaseBuilder.getDatabase(); + ds = db.start(); + } + + @After + public void tearDown() { + db.stop(); + } + + @Test + public void testConnect() throws Exception { + Connection conn = ds.getConnection(); + try { + System.out.println("Database name: " + conn.getMetaData().getDatabaseProductName()); + } finally { + conn.close(); + } + } + + @Test + public void testUseASecondTimeInTheSameTestCase() throws Exception { + testConnect(); + tearDown(); + setUp(); + testConnect(); + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/ExternalDatabaseTest.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/ExternalDatabaseTest.java new file mode 100644 index 00000000..dbe5800b --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/ExternalDatabaseTest.java @@ -0,0 +1,53 @@ +package org.wamblee.support.persistence; + +import java.sql.Connection; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.support.persistence.DatabaseProvider; +import org.wamblee.support.persistence.ExternalDatabase; + +import static junit.framework.TestCase.*; + +public class ExternalDatabaseTest { + + @Test + public void testExternalDB() throws Exception { + // Connect to inmemory db using External database class. + + Database inmemory = DatabaseBuilder + .getDatabase(DatabaseProvider.CAPABILITY_IN_MEMORY); + try { + inmemory.start(); + + System.setProperty(ExternalDatabase.DB_URL_PROP, inmemory + .getExternalJdbcUrl()); + System.setProperty(ExternalDatabase.DB_USER_PROP, inmemory + .getUsername()); + System.setProperty(ExternalDatabase.DB_PASSWORD_PROP, inmemory + .getPassword()); + + Database external = DatabaseBuilder + .getDatabase(DatabaseProvider.CAPABILITY_EXTERNAL); + assertTrue(external instanceof ExternalDatabase); + try { + DataSource ds = external.start(); + Connection conn = ds.getConnection(); + try { + System.out.println("Database name: " + + conn.getMetaData().getDatabaseProductName()); + } finally { + conn.close(); + } + } finally { + external.stop(); + } + } finally { + inmemory.stop(); + } + + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntity.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntity.java new file mode 100644 index 00000000..c2b47288 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntity.java @@ -0,0 +1,39 @@ +package org.wamblee.support.persistence; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "XYZ_MYENTITY") +public class MyEntity { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String sleuteltje; + private String value; + + + public MyEntity() { + // Empty + } + + public MyEntity(String aKey, String aValue) { + sleuteltje = aKey; + value = aValue; + } + + public String getKey() { + return sleuteltje; + } + + public String getValue() { + return value; + } + + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntityExampleTestBase.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntityExampleTestBase.java new file mode 100644 index 00000000..77f6114a --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyEntityExampleTestBase.java @@ -0,0 +1,87 @@ +package org.wamblee.support.persistence; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.dbunit.DataSourceDatabaseTester; +import org.dbunit.DatabaseTestCase; +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.JpaTester; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +import static junit.framework.Assert.*; + + +/** + * This class shows an example of how to test an entity using jpa. + */ +public class MyEntityExampleTestBase { + + // This is the magical object that does all the test setup. + private JpaTester jpaTester; + + // The jpa tester initializes a lot for us.... + + // A JPA builder that provides a transaction scoped entity manager for us. + private JpaBuilder builder; + + // The database tester for dbunit which is appropriately configured for our persistence unit. + private IDatabaseTester dbtester; + + // Database utilities with some additional functionality for working with the databse + // such as dropping tables, cleaning tables, etc. + private DatabaseUtils dbutils; + + @Before + public void setUp() throws Exception { + + // First we create the JpaTester by telling us which persistence unit we are going to test + jpaTester = new JpaTester(new MyPersistenceUnit()); + jpaTester.start(); + + // Retrieve some useful objects fromt he jpa tester. It also provides direct access to the datasource + // but we don't need it. We can use datbase utils if we want to execute straight JDBC calls. + builder = jpaTester.getJpaBuilder(); + dbtester = jpaTester.getDbTester(); + dbutils = jpaTester.getDbUtils(); + } + + @After + public void tearDown() { + jpaTester.stop(); + } + + @Test + public void testEntityPersistence() throws Exception { + + // Use the JPA builder to create a transaction scoped entity manager for as and execute the + // unit of work. + builder.execute(new JpaUnitOfWork() { + public Void execute(EntityManager em) { + MyEntity entity = new MyEntity("a", "b"); + em.persist(entity); + return null; + } + }); + + // Verify one row is written (using Db unit) + ITable table = dbtester.getDataSet().getTable("XYZ_MYENTITY"); + assertEquals(1, table.getRowCount()); + + assertEquals("a", table.getValue(0, "SLEUTELTJE")); + assertEquals("b", table.getValue(0, "VALUE")); + + // For this simple test, it can also be done through DatabaseUtils + assertEquals(1, dbutils.getTableSize("XYZ_MYENTITY")); + + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyPersistenceUnit.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyPersistenceUnit.java new file mode 100644 index 00000000..777dd882 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyPersistenceUnit.java @@ -0,0 +1,15 @@ +package org.wamblee.support.persistence; + +import org.wamblee.support.persistence.PersistenceUnitDescription; + +/** + * This class describes the persistence unit that we are testing. + */ +public class MyPersistenceUnit extends PersistenceUnitDescription { + private static final String JNDI_NAME = "wamblee/support/test"; + private static final String PERSISTENCE_UNIT_NAME = "org.wamblee.jee.support-test"; + + public MyPersistenceUnit() { + super(JNDI_NAME, PERSISTENCE_UNIT_NAME, new MyTables()); + } +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyTables.java b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyTables.java new file mode 100644 index 00000000..1283a8ff --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/java/org/wamblee/support/persistence/MyTables.java @@ -0,0 +1,25 @@ +package org.wamblee.support.persistence; + +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + +/** + * This class describes the tables we are testing. + * This implementation selects all tables with the "XYZ" prefix. + */ +public class MyTables implements ITableFilterSimple { + + /** + * + * @param aJpaTables Specific tables used by the JPA provider in addition to those for the + * entities. + */ + public MyTables() { + // Empty. + } + + public boolean accept(String tableName) throws DataSetException { + return tableName.startsWith("XYZ_"); + } + +} diff --git a/tags/wamblee-utils-0.2/test/enterprise/src/test/resources/META-INF/persistence.xml b/tags/wamblee-utils-0.2/test/enterprise/src/test/resources/META-INF/persistence.xml new file mode 100644 index 00000000..c2528813 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/enterprise/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,40 @@ + + + + wamblee/support/test + org.wamblee.support.persistence.MyEntity + + + + + + + + + + + + + + + + + diff --git a/tags/wamblee-utils-0.2/test/hibernate/pom.xml b/tags/wamblee-utils-0.2/test/hibernate/pom.xml new file mode 100644 index 00000000..a7cc21fa --- /dev/null +++ b/tags/wamblee-utils-0.2/test/hibernate/pom.xml @@ -0,0 +1,48 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-test-hibernate + jar + /test/hibernate + http://wamblee.org + + + + org.wamblee + wamblee-test-enterprise + 0.2 + + + + org.wamblee + wamblee-test-enterprise + 0.2 + test-jar + + + + org.dbunit + dbunit + + + + javax.persistence + persistence-api + + + + org.wamblee + wamblee-hibernate-jpa + 0.2 + + + + + diff --git a/tags/wamblee-utils-0.2/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java b/tags/wamblee-utils-0.2/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java new file mode 100644 index 00000000..fa4def8f --- /dev/null +++ b/tags/wamblee-utils-0.2/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateJpaCustomizer.java @@ -0,0 +1,31 @@ +package org.wamblee.support.persistence.hibernate; + +import java.util.Map; + +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.wamblee.support.persistence.JpaCustomizer; +import org.wamblee.support.persistence.PersistenceUnitDescription; + +public class HibernateJpaCustomizer implements JpaCustomizer { + + public HibernateJpaCustomizer() { + // Empty + } + + @Override + public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + // Hibernate: Override transaction type and datasource + aJpaProperties.put("javax.persistence.transactionType", "RESOURCE_LOCAL"); + aJpaProperties.put("javax.persistence.jtaDataSource", null); + aJpaProperties.put("javax.persistence.nonJtaDataSource", aPersistenceUnit.getJndiName()); + + // Hibernate schema generation + aJpaProperties.put("hibernate.hbm2ddl.auto", "create"); + } + + @Override + public ITableFilterSimple getJpaTables() { + return new HibernateTables(); + } + +} diff --git a/tags/wamblee-utils-0.2/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java b/tags/wamblee-utils-0.2/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java new file mode 100644 index 00000000..4b2c8a09 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/hibernate/src/main/java/org/wamblee/support/persistence/hibernate/HibernateTables.java @@ -0,0 +1,20 @@ +package org.wamblee.support.persistence.hibernate; + +import java.util.Arrays; +import java.util.List; + +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + +/** + * Toplink-specific tables. + */ +public class HibernateTables implements ITableFilterSimple { + + private static final List TABLES = Arrays.asList(new String[] { "" } ); + + public boolean accept(String aTableName) throws DataSetException { + return TABLES.contains(aTableName); + } + +} diff --git a/tags/wamblee-utils-0.2/test/hibernate/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer b/tags/wamblee-utils-0.2/test/hibernate/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer new file mode 100644 index 00000000..d057634d --- /dev/null +++ b/tags/wamblee-utils-0.2/test/hibernate/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer @@ -0,0 +1 @@ +org.wamblee.support.persistence.hibernate.HibernateJpaCustomizer diff --git a/tags/wamblee-utils-0.2/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java b/tags/wamblee-utils-0.2/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java new file mode 100644 index 00000000..68edf22a --- /dev/null +++ b/tags/wamblee-utils-0.2/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/DatabaseUtilsTest.java @@ -0,0 +1,23 @@ +package org.wamblee.support.persistence.hibernate; + +import static junit.framework.Assert.assertEquals; + +import javax.persistence.EntityManager; +import javax.sql.DataSource; + +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.DatabaseUtilsTestBase; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.PersistenceUnitDescription; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +public class DatabaseUtilsTest extends DatabaseUtilsTestBase { + // Empty, all tests inherited +} diff --git a/tags/wamblee-utils-0.2/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java b/tags/wamblee-utils-0.2/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java new file mode 100644 index 00000000..537cb549 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/hibernate/src/test/java/org/wamblee/support/persistence/hibernate/MyEntityExampleTest.java @@ -0,0 +1,29 @@ +package org.wamblee.support.persistence.hibernate; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.dbunit.DataSourceDatabaseTester; +import org.dbunit.DatabaseTestCase; +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.JpaTester; +import org.wamblee.support.persistence.MyEntityExampleTestBase; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +import static junit.framework.Assert.*; + + +/** + * This class shows an example of how to test an entity using jpa. + */ +public class MyEntityExampleTest extends MyEntityExampleTestBase { + // Empty, all tests are inherited +} diff --git a/tags/wamblee-utils-0.2/test/pom.xml b/tags/wamblee-utils-0.2/test/pom.xml new file mode 100644 index 00000000..bc336968 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/pom.xml @@ -0,0 +1,36 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-test + pom + /test + http://wamblee.org + + + enterprise + hibernate + + + + + all + + + !performRelease + + + + eclipselink + toplink-essentials + + + + + diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/pom.xml b/tags/wamblee-utils-0.2/test/toplink-essentials/pom.xml new file mode 100644 index 00000000..774d8a47 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/pom.xml @@ -0,0 +1,58 @@ + + + + org.wamblee + wamblee-utils + 0.2 + + + 4.0.0 + org.wamblee + wamblee-test-toplink-essentials + jar + /test/toplinkessentials + http://wamblee.org + + + + org.wamblee + wamblee-test-enterprise + 0.2 + + + + org.wamblee + wamblee-test-enterprise + 0.2 + test-jar + + + + org.dbunit + dbunit + + + + javax.persistence + persistence-api + + + + toplink.essentials + toplink-essentials + + + + + + + + javaee + Java EE repo at SUN + http://download.java.net/maven/1 + legacy + + + + + diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java new file mode 100644 index 00000000..814fe593 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/JndiSessionCustomizer.java @@ -0,0 +1,59 @@ +package org.wamblee.support.persistence.toplink; + +import javax.naming.Context; +import javax.naming.InitialContext; + +import oracle.toplink.essentials.jndi.JNDIConnector; +import oracle.toplink.essentials.sessions.DatabaseLogin; +import oracle.toplink.essentials.sessions.Session; +import oracle.toplink.essentials.threetier.ServerSession; +import oracle.toplink.essentials.tools.sessionconfiguration.SessionCustomizer; + +/** + * See http://wiki.eclipse.org/Customizing_the_EclipseLink_Application_(ELUG) Use for clients that would like to use a + * JTA SE pu instead of a RESOURCE_LOCAL SE pu. + * + * This utility also makes sure that using a persistence.xml with a JTA datasource works in a standalone Java SE + * environment together with our JNDI stub. + */ +public class JndiSessionCustomizer + implements SessionCustomizer { + + public JndiSessionCustomizer() { + // Empty. + } + + /** + * Get a dataSource connection and set it on the session with lookupType=STRING_LOOKUP + */ + public void customize(Session session) throws Exception { + JNDIConnector connector = null; + Context context = null; + try { + context = new InitialContext(); + if(null != context) { + connector = (JNDIConnector)session.getLogin().getConnector(); // possible CCE + // Change from COMPOSITE_NAME_LOOKUP to STRING_LOOKUP + // Note: if both jta and non-jta elements exist this will only change the first one - and may still result in + // the COMPOSITE_NAME_LOOKUP being set + // Make sure only jta-data-source is in persistence.xml with no non-jta-data-source property set + connector.setLookupType(JNDIConnector.STRING_LOOKUP); + + // Or, if you are specifying both JTA and non-JTA in your persistence.xml then set both connectors to be safe + JNDIConnector writeConnector = (JNDIConnector)session.getLogin().getConnector(); + writeConnector.setLookupType(JNDIConnector.STRING_LOOKUP); + JNDIConnector readConnector = + (JNDIConnector)((DatabaseLogin)((ServerSession)session).getReadConnectionPool().getLogin()).getConnector(); + readConnector.setLookupType(JNDIConnector.STRING_LOOKUP); + + System.out.println("JndiSessionCustomizer: configured " + connector.getName()); + } + else { + throw new Exception("JndiSessionCustomizer: Context is null"); + } + } + catch(Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java new file mode 100644 index 00000000..5ba15e84 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkJpaCustomizer.java @@ -0,0 +1,30 @@ +package org.wamblee.support.persistence.toplink; + +import java.util.Map; + +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.wamblee.support.persistence.JpaCustomizer; +import org.wamblee.support.persistence.PersistenceUnitDescription; + +public class ToplinkJpaCustomizer implements JpaCustomizer { + + public ToplinkJpaCustomizer() { + // Empty + } + + @Override + public void customize(PersistenceUnitDescription aPersistenceUnit, Map aJpaProperties) { + // Hack to make JNDI lookup of the datasource work with toplink + aJpaProperties.put("toplink.session.customizer", JndiSessionCustomizer.class + .getName()); + + // DDL generation for toplink + aJpaProperties.put("toplink.ddl-generation", "create-tables"); + } + + @Override + public ITableFilterSimple getJpaTables() { + return new ToplinkTables(); + } + +} diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java new file mode 100644 index 00000000..cd3a0562 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/java/org/wamblee/support/persistence/toplink/ToplinkTables.java @@ -0,0 +1,20 @@ +package org.wamblee.support.persistence.toplink; + +import java.util.Arrays; +import java.util.List; + +import org.dbunit.dataset.DataSetException; +import org.dbunit.dataset.filter.ITableFilterSimple; + +/** + * Toplink-specific tables. + */ +public class ToplinkTables implements ITableFilterSimple { + + private static final List TABLES = Arrays.asList(new String[] { "SEQUENCE" } ); + + public boolean accept(String aTableName) throws DataSetException { + return TABLES.contains(aTableName); + } + +} diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer new file mode 100644 index 00000000..82d1265a --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/src/main/resources/META-INF/services/org.wamblee.support.persistence.JpaCustomizer @@ -0,0 +1 @@ +org.wamblee.support.persistence.toplink.ToplinkJpaCustomizer diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java b/tags/wamblee-utils-0.2/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java new file mode 100644 index 00000000..095109d3 --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/DatabaseUtilsTest.java @@ -0,0 +1,23 @@ +package org.wamblee.support.persistence.toplink; + +import static junit.framework.Assert.assertEquals; + +import javax.persistence.EntityManager; +import javax.sql.DataSource; + +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.Database; +import org.wamblee.support.persistence.DatabaseBuilder; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.DatabaseUtilsTestBase; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.PersistenceUnitDescription; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +public class DatabaseUtilsTest extends DatabaseUtilsTestBase { + // Empty, all tests inherited +} diff --git a/tags/wamblee-utils-0.2/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java b/tags/wamblee-utils-0.2/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java new file mode 100644 index 00000000..415ee70f --- /dev/null +++ b/tags/wamblee-utils-0.2/test/toplink-essentials/src/test/java/org/wamblee/support/persistence/toplink/MyEntityExampleTest.java @@ -0,0 +1,29 @@ +package org.wamblee.support.persistence.toplink; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.dbunit.DataSourceDatabaseTester; +import org.dbunit.DatabaseTestCase; +import org.dbunit.IDatabaseTester; +import org.dbunit.dataset.ITable; +import org.dbunit.dataset.filter.ITableFilterSimple; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.wamblee.support.persistence.DatabaseUtils; +import org.wamblee.support.persistence.JpaBuilder; +import org.wamblee.support.persistence.JpaTester; +import org.wamblee.support.persistence.MyEntityExampleTestBase; +import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork; + +import static junit.framework.Assert.*; + + +/** + * This class shows an example of how to test an entity using jpa. + */ +public class MyEntityExampleTest extends MyEntityExampleTestBase { + // Empty, all tests are inherited +}