diff --git a/.classpath b/.classpath deleted file mode 100644 index 461d9623..00000000 --- a/.classpath +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ef644755 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target/ +derby.log \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 03476b75..00000000 --- a/.project +++ /dev/null @@ -1,18 +0,0 @@ - - - - graffito-jcr-mapping - This subproject contains the JCR Mapping tools - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/LICENSE.txt @@ -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/NOTICE.txt b/NOTICE.txt new file mode 100644 index 00000000..514416eb --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Jackrabbit Object Content Mapping +Copyright 2009 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/README.txt b/README.txt new file mode 100644 index 00000000..560ea97c --- /dev/null +++ b/README.txt @@ -0,0 +1,49 @@ +=============================================== +Apache Jackrabbit Object Content Mapping + +=============================================== + +Object Content Mapping (OCM) is an object/JCR persistence and query service. +This tools lets you to persist Java objects into a JCR compliant repository +- including association, inheritance, polymorphism, composition, and the +Java Collections framework. + +Furthermore, this object-content mapping component allows you to express +queries with Java-based criteria, as well as in JCR query language. It +offers also features like version support and object locking. + +OCM is a part of the JCR Commons subproject of Apache Jackrabbit. +Jackrabbit is a project of the Apache Software Foundation. + +Build instructions +================== + +To build OCM, run the following command in this directory: + + mvn clean install + +You need Java 5 (or higher) and Maven 2.0.9 (or higher) to do this. + +After the build finishes successfully, you can find the compiled OCM +component in ./target/. The component will also have been installed in your +local Maven repository. + +License (see also LICENSE.txt) +============================== + +Collective work: Copyright 2009 The Apache Software Foundation. + +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT 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/RELEASE-NOTES.txt b/RELEASE-NOTES.txt new file mode 100644 index 00000000..6c0959bb --- /dev/null +++ b/RELEASE-NOTES.txt @@ -0,0 +1,54 @@ +Release Notes -- Apache Jackrabbit OCM -- Version 2.0.0 + +Introduction +------------ + +This is Apache Jackrabbit OCM 2.0, a subproject of Apache Jackrabbit + +Apache Jackrabbit OCM 2.0.0 is release that contains fixes and +improvements over Jackrabbit OCM 1.5. Apart from the test classes, it +does not depend on Apache Jackrabbit core, but only on the JCR 2.0 specification + +Changes since Jackrabbit 1.5 +------------------------------ +Improvements + [OCM-49] ObjectContentManagerImpl should not use workspace move but rather do it through the jcr session + [OCM-51] Replace itemExists and getItem logic in ObjectConverterImpl and ObjectContentManagerImpl to nodeExists and getNode + [OCM-43] Reviving OCM framework with Jackrabbit 2.x + [OCM-52] Replace inefficient ObjectContentManagerImpl#getObjects(Class objectClass, String path) path .... + [OCM-58] Make OCM jackrabbit independent and rely on JCR 2.0 only + [OCM-54] ObjectContentManagerImpl should not use workspace copy but rather do it through the jcr session + [OCM-55] Replace commons logging LogFactory with slf4j LoggerFactory + + +Bug fixes + [OCM-53] Fixes needed to work with latest jr 2.4.1 tag + [OCM-50] AnnotationDescriptorReader in case of a @Collection annotation incorrectly .... + [OCM-48] DefaultCollectionConverterImpl should take nodetype into account for doInsertCollection .... + [OCM-42] OCM Versioning is not working as expected + [OCM-33] Running the tests without "mvn clean" provides errors + [OCM-45] ReflectionUtils.implementsInterface() only checks one interface and returns + [OCM-40] Doesn't compile with jackrabbit 2.0.0 + [OCM-59] Run all unit tests against an in memory repository and extend from AbstractJcrTestCase + [OCM-34] referential integrity problem due to ObjectContentManagerImpl usage of ObjectCache + [OCM-44] getObjectByUuid throws exception instead of returning null as described in javadoc + +New features + +Tasks + [OCM-56] Remove UserTransactionImpl tests for transactions from OCM project + [OCM-1] Move jackrabbit-ocm to JCR Commons + [OCM-57] Cleanup exceptions that are outdated or not needed any more + + +About The Apache Software Foundation +------------------------------------ + +Established in 1999, The Apache Software Foundation provides organizational, +legal, and financial support for more than 100 freely-available, +collaboratively-developed Open Source projects. The pragmatic Apache License +enables individual and commercial users to easily deploy Apache software; +the Foundation's intellectual property framework limits the legal exposure +of its 2,500+ contributors. + +For more information, visit http://www.apache.org/ diff --git a/locator.ent b/locator.ent deleted file mode 100644 index 90b562ad..00000000 --- a/locator.ent +++ /dev/null @@ -1,2 +0,0 @@ - - %locator-ent; diff --git a/locator.path b/locator.path deleted file mode 100644 index 6581736d..00000000 --- a/locator.path +++ /dev/null @@ -1 +0,0 @@ -../../ \ No newline at end of file diff --git a/maven.xml b/maven.xml deleted file mode 100644 index b7c44055..00000000 --- a/maven.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/nbactions.xml b/nbactions.xml new file mode 100644 index 00000000..e042184a --- /dev/null +++ b/nbactions.xml @@ -0,0 +1,26 @@ + + + + CUSTOM-Deploy + Deploy + false + + deploy + + + true + + + + CUSTOM-Build + Build + false + + clean + install + + + true + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..6a453ddd --- /dev/null +++ b/pom.xml @@ -0,0 +1,271 @@ + + + + + + 4.0.0 + + + org.apache + apache + 10 + + + + jackrabbit-ocm + 3.0.3 + Jackrabbit Object Content Mapping 2.x + + This Jackrabbit subproject is an object/JCR persistence and + query service. This tools lets you to persist java objects into + a JCR compliant repository - including association, inheritance, + polymorphism, composition, and the Java collections framework. + Furthermore, this jcr-mapping allows you to express queries in + Java-based Criteria, as well as in JCR query language. It offers + also features like version support and object locking. + + http://jackrabbit.apache.org/object-content-mapping.html + 2004 + + + 2.0 + 2.8.0 + 2.1 + 2.6 + 3.2.1 + 1.7.0 + 1.7.5 + 4.7 + 2.9.1 + + + + + scm:svn:http://svn.apache.org/repos/asf/jackrabbit/commons/ocm/trunk + scm:svn:https://svn.apache.org/repos/asf/jackrabbit/commons/ocm/trunk + http://svn.apache.org/viewvc/asf/jackrabbit/commons/ocm/trunk + + + + + + Jackrabbit Developer List + dev-subscribe@jackrabbit.apache.org + dev-unsubscribe@jackrabbit.apache.org + mailto:dev@jackrabbit.apache.org + http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/ + + + + Jackrabbit User List + users-subscribe@jackrabbit.apache.org + users-unsubscribe@jackrabbit.apache.org + mailto:users@jackrabbit.apache.org + http://mail-archives.apache.org/mod_mbox/jackrabbit-users/ + + + + + + https://issues.apache.org/jira/browse/OCM + + + + + + pedantic + + + + org.apache.rat + apache-rat-plugin + + + verify + + check + + + + + + + + + + + + + + + + + maven-compiler-plugin + + 1.5 + 1.5 + true + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + + maven-surefire-plugin + + + + org.apache.jackrabbit.repository.home + target/repository + + + + + + + org.apache.rat + apache-rat-plugin + + + derby.log + + + + + + + + + + + + + + javax.jcr + jcr + ${javax.jcr.version} + + + commons-digester + commons-digester + ${commons.digester.version} + + + commons-logging + commons-logging + + + + + commons-collections + commons-collections + ${commons.collection.version} + + + commons-lang + commons-lang + ${commons.lang.version} + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + cglib + cglib + 2.2 + + + + commons-beanutils + commons-beanutils + ${commons.beanutils.version} + + + commons-logging + commons-logging + + + + + + + + org.apache.jackrabbit + jackrabbit-core + ${apache.jackrabbit.version} + test + + + + org.apache.jackrabbit + jackrabbit-jcr-tests + ${apache.jackrabbit.version} + test + + + + junit + junit + ${junit.version} + test + + + org.slf4j + slf4j-log4j12 + ${org.slf4j.version} + test + + + xerces + xercesImpl + ${xerces.version} + test + + + + + + + internal + Internal Release Repository + http://mvn:8080/archiva/repository/internal/ + + + snapshots + Internal Snapshot Repository + http://mvn:8080/archiva/repository/snapshots/ + + + + + diff --git a/project.properties b/project.properties deleted file mode 100644 index 6234e5a0..00000000 --- a/project.properties +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright 2004 The Apache Software Foundation -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#----------------------------------------------------------------------------------------------------- -# MAVEN REPORISTORIES -#----------------------------------------------------------------------------------------------------- -maven.repo.remote = http://www.bluesunrise.com/maven/, http://www.ibiblio.org/maven/, http://dist.codehaus.org/, http://cvs.apache.org/repository - -#----------------------------------------------------------------------------------------------------- -# MULTIPROJECTS -#----------------------------------------------------------------------------------------------------- -maven.multiproject.type=jar -maven.license.licenseFile=../../LICENSE.TXT -#----------------------------------------------------------------------------------------------------- -# DOC : SITE & PDF DOC -#----------------------------------------------------------------------------------------------------- -maven.docs.dest=${basedir}/../../../site/jcr-mapping - -# Display the date on the Maven web site -maven.xdoc.date = left - -maven.xdoc.version = ${pom.currentVersion} -maven.pdf.navigationFile=navigation_pdf.xml - -#----------------------------------------------------------------------------------------------------- -# COMPILE -#----------------------------------------------------------------------------------------------------- -maven.compile.deprecation=on -#maven.compile.source=1.4 -#maven.compile.target=1.4 -#maven.test.source=1.4 diff --git a/project.xml b/project.xml deleted file mode 100644 index 6865cb1a..00000000 --- a/project.xml +++ /dev/null @@ -1,191 +0,0 @@ - - - - - ${basedir}/../../project.xml - 3 - graffito-jcr-mapping - org.apache.portals.graffito - Graffito JCR Mapping - 1.0-a1-dev - org.apache.portals.graffito - - This subproject contains the JCR Mapping tools - - Graffito JCR Mapping Tools - - - - scm:subversion:https://svn.apache.org/repos/asf/incubator/graffito/trunk/jcr/jcr-mapping - - - scm:subversion:https://svn.apache.org/repos/asf/incubator/graffito/trunk/jcr/jcr-mapping - - http://svn.apache.org/viewcvs - - - - - - org.apache.jackrabbit - jackrabbit - 1.0-20060108-SNAPSHOT - - - concurrent - concurrent - 1.3.4 - - - junit - junit - 3.8.1 - - test - - - - commons-collections - commons-collections - 3.1 - - - geronimo-spec - geronimo-spec-jta - 1.0-M1 - - - jsr170 - jcr - 1.0 - http://jcp.org/en/jsr/detail?id=170 - - - log4j - log4j - 1.2.8 - - - lucene - lucene - 1.4.3 - - - xerces - xercesImpl - 2.6.2 - - - xerces - xmlParserAPIs - 2.0.2 - - - org.apache.derby - derby - 10.1.1.0 - - - - - commons-beanutils - jar - commons-beanutils - 1.7.0 - - - - - commons-digester - jar - commons-digester - 1.7 - - - - commons-logging - 1.0.2 - http://jakarta.apache.org/commons/logging.html - - - commons-lang - commons-lang - 2.1 - jar - - true - - - - - - - - src/java - - - ${basedir}/src/test - - - - - org/apache/portals/graffito/jcr/testmodel/**/*.java - - **/*TestBase.java - - - - ${basedir}/src/test - - **/*.java - - - - - - - - ${basedir}/src/java - - **/*.java - - - - - - - - maven-javadoc-plugin - maven-changelog-plugin - maven-file-activity-plugin - maven-jcoverage-plugin - maven-changelog-plugin - maven-changes-plugin - - maven-junit-report-plugin - maven-jxr-plugin - maven-pmd-plugin - - - - diff --git a/src/docbook/test-docbook.xml b/src/docbook/test-docbook.xml deleted file mode 100644 index 73206fe0..00000000 --- a/src/docbook/test-docbook.xml +++ /dev/null @@ -1,47 +0,0 @@ - - -
Test - - -This is a test - - - - - - - - - - - - -Col1 - - -Col2 - - -Col3 - - -Col4 - - - - - -kklkl - - -kkk - - -klkl - - -kp - - - -
diff --git a/src/dtd/graffito-jcr-mapping.dtd b/src/dtd/graffito-jcr-mapping.dtd deleted file mode 100644 index 8cba6a42..00000000 --- a/src/dtd/graffito-jcr-mapping.dtd +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/src/java/org/apache/portals/graffito/jcr/exception/LockingException.java b/src/java/org/apache/portals/graffito/jcr/exception/LockingException.java deleted file mode 100644 index 8bc656dc..00000000 --- a/src/java/org/apache/portals/graffito/jcr/exception/LockingException.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - -/** - * Base exception for all exceptions related to JCR Locking feature. - * - * @author markoc - */ -abstract public class LockingException extends PersistenceException { -} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/NestableRuntimeException.java b/src/java/org/apache/portals/graffito/jcr/exception/NestableRuntimeException.java deleted file mode 100644 index 9faeca42..00000000 --- a/src/java/org/apache/portals/graffito/jcr/exception/NestableRuntimeException.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -import java.io.PrintStream; -import java.io.PrintWriter; - -/** - * Nestable runtime exception. Able to wrap a cause exception in JDK previous to 1.4 - * - * @author Spring framework - */ -public class NestableRuntimeException extends RuntimeException { - - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = -1939051127461985443L; - - /** Root cause of this nested exception */ - private Throwable cause; - - /** - * No-arg constructor used by markup exceptions. - */ - protected NestableRuntimeException() { - } - - /** - * Construct a NestableRuntimeException with the specified detail message. - * @param msg the detail message - */ - public NestableRuntimeException(String msg) { - super(msg); - } - - /** - * Construct a NestableRuntimeException with the specified detail message - * and nested exception. - * @param msg the detail message - * @param ex the nested exception - */ - public NestableRuntimeException(String msg, Throwable ex) { - super(msg); - this.cause = ex; - } - - /** - * Construct a NestableRuntimeException with the specified - * nested exception. - * - * @param ex the nested exception - */ - public NestableRuntimeException(Throwable ex) { - this.cause = ex; - } - - /** - * Return the nested cause, or null if none. - */ - public Throwable getCause() { - // Even if you cannot set the cause of this exception other than through - // the constructor, we check for the cause being "this" here, as the cause - // could still be set to "this" via reflection: for example, by a remoting - // deserializer like Hessian's. - return ((this.cause == this) ? null : this.cause); - } - - /** - * Return the detail message, including the message from the nested exception - * if there is one. - */ - public String getMessage() { - if (getCause() == null) { - return super.getMessage(); - } else { - return super.getMessage() - + "; nested exception is " - + getCause().getClass().getName() - + ": " + getCause().getMessage(); - } - } - - /** - * Print the composite message and the embedded stack trace to the specified stream. - * @param ps the print stream - */ - public void printStackTrace(PrintStream ps) { - if (getCause() == null) { - super.printStackTrace(ps); - } else { - ps.println(this); - getCause().printStackTrace(ps); - } - } - - /** - * Print the composite message and the embedded stack trace to the specified writer. - * @param pw the print writer - */ - public void printStackTrace(PrintWriter pw) { - if (getCause() == null) { - super.printStackTrace(pw); - } else { - pw.println(this); - getCause().printStackTrace(pw); - } - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/Mapper.java b/src/java/org/apache/portals/graffito/jcr/mapper/Mapper.java deleted file mode 100644 index 3f1fe272..00000000 --- a/src/java/org/apache/portals/graffito/jcr/mapper/Mapper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper; - -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; - -/** - * This component read the mapping file and gives an access to the ClassDescriptors (the mapping object model) - * - * @author Lombart Christophe - * - */ -public interface Mapper -{ - /** - * Get the mapping defition to be used for a specific java bean - * @param clazz The java bean class - * @return The mapping class found for the desired java bean class - */ - public abstract ClassDescriptor getClassDescriptor(Class clazz); -} \ No newline at end of file diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/impl/DigesterDescriptorReader.java b/src/java/org/apache/portals/graffito/jcr/mapper/impl/DigesterDescriptorReader.java deleted file mode 100644 index ac0f0b2b..00000000 --- a/src/java/org/apache/portals/graffito/jcr/mapper/impl/DigesterDescriptorReader.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2000-20045 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper.impl; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; - -import org.apache.commons.digester.Digester; -import org.apache.portals.graffito.jcr.exception.InitMapperException; -import org.apache.portals.graffito.jcr.mapper.model.BeanDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.FieldDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.MappingDescriptor; - -/** - * Helper class that reads the xml mapping file and load all class descriptors into memory (object graph) - * - * @author Lombart Christophe - * - */ -public class DigesterDescriptorReader -{ - /** - * Load all class descriptors found in the xml mapping file. - * - * @param stream the xml mapping file reference - * @return a {@link MappingDescriptor} - * - */ - public static MappingDescriptor loadClassDescriptors(InputStream stream) - { - try - { - Digester digester = new Digester(); - digester.setValidating(true); - - digester.addObjectCreate("graffito-jcr", MappingDescriptor.class); - - // -------------------------------------------------------------------------------- - // Rules used for the class-descriptor element - // -------------------------------------------------------------------------------- - - digester.addObjectCreate("graffito-jcr/class-descriptor", ClassDescriptor.class); - digester.addSetProperties("graffito-jcr/class-descriptor", "className", "className"); - digester.addSetProperties("graffito-jcr/class-descriptor", "jcrNodeType", "jcrNodeType"); - digester.addSetProperties("graffito-jcr/class-descriptor", "jcrSuperTypes", "jcrSuperTypes"); - - digester.addSetNext("graffito-jcr/class-descriptor", "addClassDescriptor"); - - // -------------------------------------------------------------------------------- - // Rules used for the field-descriptor element - // -------------------------------------------------------------------------------- - - digester.addObjectCreate("graffito-jcr/class-descriptor/field-descriptor", FieldDescriptor.class); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "fieldName", "fieldName"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "fieldType", "fieldType"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrName", "jcrName"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "id", "id"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "path", "path"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrType", "jcrType"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrAutoCreated", "jcrAutoCreated"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrMandatory", "jcrMandatory"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrOnParentVersion", "jcrOnParentVersion"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrProtected", "jcrProtected"); - digester.addSetProperties("graffito-jcr/class-descriptor/field-descriptor", "jcrMultiple", "jcrMultiple"); - digester.addSetNext("graffito-jcr/class-descriptor/field-descriptor", "addFieldDescriptor"); - - // -------------------------------------------------------------------------------- - // Rules used for the bean-descriptor element - // -------------------------------------------------------------------------------- - - digester.addObjectCreate("graffito-jcr/class-descriptor/bean-descriptor", BeanDescriptor.class); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "fieldName", "fieldName"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrName", "jcrName"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "proxy", "proxy"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrNodeType", "jcrNodeType"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrAutoCreated", "jcrAutoCreated"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrMandatory", "jcrMandatory"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrOnParentVersion", "jcrOnParentVersion"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrProtected", "jcrProtected"); - digester.addSetProperties("graffito-jcr/class-descriptor/bean-descriptor", "jcrSameNameSiblings", "jcrSameNameSiblings"); - digester.addSetNext("graffito-jcr/class-descriptor/bean-descriptor", "addBeanDescriptor"); - - // -------------------------------------------------------------------------------- - // Rules used for the collection-descriptor element - // -------------------------------------------------------------------------------- - - digester.addObjectCreate("graffito-jcr/class-descriptor/collection-descriptor", CollectionDescriptor.class); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "fieldName", "fieldName"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrName", "jcrName"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "proxy", "proxy"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "elementClassName", "elementClassName"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "collectionConverter", "collectionConverterClassName"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "collectionClassName", "collectionClassName"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrNodeType", "jcrNodeType"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrAutoCreated", "jcrAutoCreated"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrMandatory", "jcrMandatory"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrOnParentVersion", "jcrOnParentVersion"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrProtected", "jcrProtected"); - digester.addSetProperties("graffito-jcr/class-descriptor/collection-descriptor", "jcrSameNameSiblings", "jcrSameNameSiblings"); - digester.addSetNext("graffito-jcr/class-descriptor/collection-descriptor", "addCollectionDescriptor"); - - MappingDescriptor mappingDescriptor = (MappingDescriptor) digester.parse(stream); - return mappingDescriptor; - } - catch (Exception e) - { - throw new InitMapperException("Impossible to read the xml mapping file", e); - } - } - - /** - * Load all class descriptors found in the xml mapping file. - * - * @param xmlFile the xml mapping file reference - * @return a {@link MappingDescriptor} - * - */ - public static MappingDescriptor loadClassDescriptors(String xmlFile) - { - try - { - return loadClassDescriptors(new FileInputStream(xmlFile)); - } - catch (FileNotFoundException e) - { - throw new InitMapperException(e); - } - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/impl/DigesterMapperImpl.java b/src/java/org/apache/portals/graffito/jcr/mapper/impl/DigesterMapperImpl.java deleted file mode 100644 index b2ff1eab..00000000 --- a/src/java/org/apache/portals/graffito/jcr/mapper/impl/DigesterMapperImpl.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper.impl; - -import java.io.InputStream; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.MappingDescriptor; - -/** - * - * Digester implementation for {@link org.apache.portals.graffito.jcr.mapper.Mapper} - * - * @author Lombart Christophe - */ -public class DigesterMapperImpl implements Mapper -{ - private MappingDescriptor mappingDescriptor; - private Log log = LogFactory.getLog(DigesterMapperImpl.class); - - /** - * Constructor - * - * @param xmlFile The xml mapping file to read - * - */ - public DigesterMapperImpl(String xmlFile) - { - log.info("Read the xml mapping file : " + xmlFile); - mappingDescriptor = DigesterDescriptorReader.loadClassDescriptors(xmlFile); - } - - /** - * Constructor - * - * @param files a set of xml mapping files to read - * - */ - public DigesterMapperImpl(String[] files) - { - log.info("Read the xml mapping file : " + files[0]); - mappingDescriptor = DigesterDescriptorReader.loadClassDescriptors(files[0]); - for (int i=1; iLombart Christophe - * - */ -public class BeanDescriptor -{ - - private String fieldName; - private String jcrName; - private boolean proxy; - private String jcrNodeType; - private boolean jcrAutoCreated; - private boolean jcrMandatory; - private String jcrOnParentVersion; - private boolean jcrProtected; - private boolean jcrSameNameSiblings; - - /** - * @return Returns the fieldName. - */ - public String getFieldName() - { - return fieldName; - } - /** - * @param fieldName The fieldName to set. - */ - public void setFieldName(String fieldName) - { - this.fieldName = fieldName; - } - /** - * @return Returns the jcrName. - */ - public String getJcrName() - { - return jcrName; - } - /** - * @param jcrName The jcrName to set. - */ - public void setJcrName(String jcrName) - { - this.jcrName = jcrName; - } - - - /** - * @return Returns the proxy. - */ - public boolean isProxy() - { - return proxy; - } - /** - * @param proxy The proxy to set. - */ - public void setProxy(boolean proxy) - { - this.proxy = proxy; - } - - /** Getter for property jcrNodeType. - * - * @return jcrNodeType - */ - public String getJcrNodeType() - { - return jcrNodeType; - } - - /** Setter for property jcrNodeType. - * - * @param value jcrNodeType - */ - public void setJcrNodeType(String value) - { - this.jcrNodeType = value; - } - - /** Getter for property jcrAutoCreated. - * - * @return jcrAutoCreated - */ - public boolean isJcrAutoCreated() - { - return jcrAutoCreated; - } - - /** Setter for property jcrAutoCreated. - * - * @param value jcrAutoCreated - */ - public void setJcrAutoCreated(boolean value) - { - this.jcrAutoCreated = value; - } - - /** Getter for property jcrMandatory. - * - * @return jcrMandatory - */ - public boolean isJcrMandatory() - { - return jcrMandatory; - } - - /** Setter for property jcrMandatory. - * - * @param value jcrMandatory - */ - public void setJcrMandatory(boolean value) - { - this.jcrMandatory = value; - } - - /** Getter for property jcrOnParentVersion. - * - * @return jcrOnParentVersion - */ - public String getJcrOnParentVersion() - { - return jcrOnParentVersion; - } - - /** Setter for property jcrOnParentVersion. - * - * @param value jcrOnParentVersion - */ - public void setJcrOnParentVersion(String value) - { - this.jcrOnParentVersion = value; - } - - /** Getter for property jcrProtected. - * - * @return jcrProtected - */ - public boolean isJcrProtected() - { - return jcrProtected; - } - - /** Setter for property jcrProtected. - * - * @param value jcrProtected - */ - public void setJcrProtected(boolean value) - { - this.jcrProtected = value; - } - - /** Getter for property jcrSameNameSiblings. - * - * @return jcrSameNameSiblings - */ - public boolean isJcrSameNameSiblings() - { - return jcrSameNameSiblings; - } - - /** Setter for property jcrSameNameSiblings. - * - * @param value jcrSameNameSiblings - */ - public void setJcrSameNameSiblings(boolean value) - { - this.jcrSameNameSiblings = value; - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/model/ClassDescriptor.java b/src/java/org/apache/portals/graffito/jcr/mapper/model/ClassDescriptor.java deleted file mode 100644 index 7cd54d7b..00000000 --- a/src/java/org/apache/portals/graffito/jcr/mapper/model/ClassDescriptor.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper.model; - -import java.util.Collection; -import java.util.HashMap; - -/** - * - * ClassDescriptor is used by the mapper to read general information on a class - * - * @author Lombart Christophe - * - */ -public class ClassDescriptor -{ - - private String className; - private String jcrNodeType; - private String jcrSuperTypes; - private FieldDescriptor idFieldDescriptor; - private FieldDescriptor pathFieldDescriptor; - - private HashMap fieldDescriptors = new HashMap(); - private HashMap beanDescriptors = new HashMap(); - private HashMap collectionDescriptors = new HashMap(); - private HashMap fieldNames = new HashMap(); - - - /** - * @return Returns the className. - */ - public String getClassName() - { - return className; - } - /** - * @param className The className to set. - */ - public void setClassName(String className) - { - this.className = className; - } - - - /** - * @return Returns the jcrNodeType. - */ - public String getJcrNodeType() - { - return jcrNodeType; - } - /** - * @param jcrNodeType The jcrNodeType to set. - */ - public void setJcrNodeType(String jcrNodeType) - { - this.jcrNodeType = jcrNodeType; - } - - /** - * Add a new FielDescriptor - * @param fieldDescriptor the new field descriptor to add - */ - public void addFieldDescriptor(FieldDescriptor fieldDescriptor ) - { - fieldDescriptor.setClassDescriptor(this); - if (fieldDescriptor.isId()) - { - this.idFieldDescriptor = fieldDescriptor; - } - - if (fieldDescriptor.isPath()) - { - this.pathFieldDescriptor = fieldDescriptor; - } - - fieldDescriptors.put(fieldDescriptor.getFieldName(), fieldDescriptor); - fieldNames.put(fieldDescriptor.getFieldName(), fieldDescriptor.getJcrName()); - } - - /** - * Get the FieldDescriptor to used for a specific java bean attribute - * @param fieldName The java bean attribute name - * - * @return the {@link FieldDescriptor} found or null - */ - public FieldDescriptor getFieldDescriptor(String fieldName) - { - return (FieldDescriptor) fieldDescriptors.get(fieldName); - } - - /** - * - * @return all {@link FieldDescriptor} defined in this ClassDescriptor - */ - public Collection getFieldDescriptors() - { - return fieldDescriptors.values(); - } - - /** - * Add a new BeanDescriptor - * @param beanDescriptor the new bean descriptor to add - */ - - public void addBeanDescriptor(BeanDescriptor beanDescriptor ) - { - beanDescriptors.put(beanDescriptor.getFieldName(), beanDescriptor); - fieldNames.put(beanDescriptor.getFieldName(), beanDescriptor.getJcrName()); - } - - /** - * Get the BeanDescriptor to used for a specific java bean attribute - * @param fieldName The java bean attribute name - * - * @return the {@link BeanDescriptor} found or null - */ - public BeanDescriptor getBeanDescriptor(String fieldName) - { - return (BeanDescriptor) beanDescriptors.get(fieldName); - } - - - /** - * @return all {@link BeanDescriptor} defined in this ClassDescriptor - */ - public Collection getBeanDescriptors() - { - return beanDescriptors.values(); - } - - - /** - * Add a new CollectionDescriptor - * @param collectionDescriptor the new collection descriptor to add - */ - - public void addCollectionDescriptor(CollectionDescriptor collectionDescriptor ) - { - collectionDescriptor.setClassDescriptor(this); - collectionDescriptors.put(collectionDescriptor.getFieldName(), collectionDescriptor); - fieldNames.put(collectionDescriptor.getFieldName(), collectionDescriptor.getJcrName()); - } - - /** - * Get the CollectionDescriptor to used for a specific java bean attribute - * @param fieldName The java bean attribute name - * - * @return the {@link CollectionDescriptor} found or null - */ - public CollectionDescriptor getCollectionDescriptor(String fieldName) - { - return (CollectionDescriptor) collectionDescriptors.get(fieldName); - } - - /** - * @return all {@link BeanDescriptor} defined in this ClassDescriptor - */ - public Collection getCollectionDescriptors() - { - return collectionDescriptors.values(); - } - - /** - * @return the fieldDescriptor ID - */ - public FieldDescriptor getIdFieldDescriptor() - { - return idFieldDescriptor; - } - - /** - * @return the fieldDescriptor path - */ - public FieldDescriptor getPathFieldDescriptor() - { - return pathFieldDescriptor; - } - - /** - * Check if this class has an ID - * @return true if the class has an ID - */ - public boolean hasIdField() - { - return this.idFieldDescriptor != null; - } - - /** - * Get the JCR name used for one of the object attributes - * @param fieldName the object attribute name (can be an atomic field, bean field or a collection field) - * @return the JCR name found - */ - public String getJcrName(String fieldName) - { - return (String) this.fieldNames.get(fieldName); - } - - /** Get the JCR node super types. - * - * @return jcrSuperTypes - */ - public String getJcrSuperTypes() - { - return jcrSuperTypes; - } - - /** Setter for JCR super types. - * - * @param superTypes Comma separated list of JCR node super types - */ - public void setJcrSuperTypes(String superTypes) - { - this.jcrSuperTypes = superTypes; - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/model/FieldDescriptor.java b/src/java/org/apache/portals/graffito/jcr/mapper/model/FieldDescriptor.java deleted file mode 100644 index ce708697..00000000 --- a/src/java/org/apache/portals/graffito/jcr/mapper/model/FieldDescriptor.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper.model; - -/** - * - * - * FieldDescriptor is used by the mapper to read general information on a atomic field - * - * @author Lombart Christophe - * - */ -public class FieldDescriptor -{ - private String fieldName; - private String fieldType; - private Class fieldTypeClass; - private String jcrName; - private String jcrType; - private boolean jcrAutoCreated; - private boolean jcrMandatory; - private String jcrOnParentVersion; - private boolean jcrProtected; - private boolean jcrMultiple; - private ClassDescriptor classDescriptor; - private boolean id; - private boolean path; - - /** - * @return Returns the fieldName. - */ - public String getFieldName() - { - return fieldName; - } - - /** - * @param fieldName The fieldName to set. - */ - public void setFieldName(String fieldName) - { - this.fieldName = fieldName; - } - - /** - * @return the primitive or fully qualified class of the field - * or null if not specified in the mapping - */ - public String getFieldType() - { - return this.fieldType; - } - - /** - * Sets the type of the field. It supports primitive types, specified as - * int, long, etc or fully qualified class names. - * - * @param fieldType the type of the field - */ - public void setFieldType(String fieldType) - { - this.fieldType = fieldType; - } - - /** - * @return the field class of the field - * or null if not specified in the mapping - * or if the class was not found - */ - public Class getFieldTypeClass() - { - if (this.fieldType == null) { - return null; - } - if (this.fieldTypeClass == null) { - this.fieldTypeClass = loadFieldTypeClass(); - } - - return this.fieldTypeClass; - } - - /** - * @return Returns the jcrName. - */ - public String getJcrName() - { - return jcrName; - } - - /** - * @param jcrName The jcrName to set. - */ - public void setJcrName(String jcrName) - { - this.jcrName = jcrName; - } - - /** - * - * @return the associated class descriptor - */ - public ClassDescriptor getClassDescriptor() - { - return classDescriptor; - } - - /** - * Set the associated class descriptor - * @param classDescriptor the class descriptor to set - */ - public void setClassDescriptor(ClassDescriptor classDescriptor) - { - this.classDescriptor = classDescriptor; - } - - /** - * @return true if the field is the class ID - */ - public boolean isId() - { - return id; - } - - /** - * - * @param id - */ - public void setId(boolean id) - { - this.id = id; - } - - /** - * @return Returns true if the field is the object JCR path. - */ - public boolean isPath() - { - return path; - } - - /** - * @param path The path to set. - */ - public void setPath(boolean path) - { - this.path = path; - } - - /** Getter for property jcrType. - * - * @return jcrType - */ - public String getJcrType() - { - return jcrType; - } - - /** Setter for property jcrType. - * - * @param value jcrType - */ - public void setJcrType(String value) - { - this.jcrType = value; - } - - /** Getter for propery jcrAutoCreated. - * - * @return jcrAutoCreated - */ - public boolean isJcrAutoCreated() - { - return jcrAutoCreated; - } - - /** Setter for property jcrAutoCreated. - * - * @param value jcrAutoCreated - */ - public void setJcrAutoCreated(boolean value) - { - this.jcrAutoCreated = value; - } - - /** Getter for property jcrMandatory. - * - * @return jcrMandatory - */ - public boolean isJcrMandatory() - { - return jcrMandatory; - } - - /** Setter for property jcrMandatory. - * - * @param value jcrMandatory - */ - public void setJcrMandatory(boolean value) - { - this.jcrMandatory = value; - } - - /** Getter for property jcrOnParentVersion. - * - * @return jcrOnParentVersion - */ - public String getJcrOnParentVersion() - { - return jcrOnParentVersion; - } - - /** Setter for property jcrOnParentVersion. - * - * @param value jcrOnParentVersion - */ - public void setJcrOnParentVersion(String value) - { - this.jcrOnParentVersion = value; - } - - /** Getter for property jcrProtected. - * - * @return jcrProtected - */ - public boolean isJcrProtected() - { - return jcrProtected; - } - - /** Setter for property jcrProtected. - * - * @param value jcrProtected - */ - public void setJcrProtected(boolean value) - { - this.jcrProtected = value; - } - - /** Getter for property jcrMultiple. - * - * @return jcrMultiple - */ - public boolean isJcrMultiple() - { - return jcrMultiple; - } - - /** Setter for property jcrMultiple. - * - * @param value jcrMultiple - */ - public void setJcrMultiple(boolean value) - { - this.jcrMultiple = value; - } - - /** - * Initialize the fieldTypeClass. - * - * @return the primitive class or the class accordign to fieldType - */ - private Class loadFieldTypeClass() { - if (this.fieldType == null) - { - return null; - } - if ("byte".equals(this.fieldType)) - { - return byte.class; - } - else if ("short".equals(this.fieldType)) - { - return short.class; - } - else if ("int".equals(this.fieldType)) - { - return int.class; - } - else if ("long".equals(this.fieldType)) - { - return long.class; - } - else if ("float".equals(this.fieldType)) - { - return float.class; - } - else if ("double".equals(this.fieldType)) - { - return double.class; - } - else if ("char".equals(this.fieldType)) - { - return char.class; - } - else if ("boolean".equals(this.fieldType)) - { - return boolean.class; - } - else - { - try { - return Class.forName(this.fieldType); - } - catch (ClassNotFoundException cnfe) - { - ; // nothing to do; it will be dynamically determined - } - } - - return null; - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/model/MappingDescriptor.java b/src/java/org/apache/portals/graffito/jcr/mapper/model/MappingDescriptor.java deleted file mode 100644 index a9b472dd..00000000 --- a/src/java/org/apache/portals/graffito/jcr/mapper/model/MappingDescriptor.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper.model; - -import java.util.HashMap; -import java.util.Map; - -/** - * This class match to the complete xml mapping files. - * it contains mainly a collection of {@link ClassDescriptor} - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class MappingDescriptor -{ - private HashMap classDescriptors = new HashMap(); - - /** - * Add a new ClassDescriptor - * - * @param classDescriptor The class descriptor to add - */ - public void addClassDescriptor(ClassDescriptor classDescriptor) - { - classDescriptors.put(classDescriptor.getClassName(), classDescriptor); - } - - /** - * Get the classdescriptor to used for the class - * @param className the class name - * @return the class descriptor found or null - */ - public ClassDescriptor getClassDescriptor(String className) - { - return (ClassDescriptor) classDescriptors.get(className); - } - - /** - * Get all class descriptors - * @return all class descriptors found - */ - public Map getClassDescriptors() - { - return classDescriptors; - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/PersistenceManager.java b/src/java/org/apache/portals/graffito/jcr/persistence/PersistenceManager.java deleted file mode 100644 index 2652171b..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/PersistenceManager.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence; - -import java.util.Collection; -import java.util.Iterator; - -import javax.jcr.version.VersionException; - -import org.apache.portals.graffito.jcr.exception.IllegalUnlockException; -import org.apache.portals.graffito.jcr.exception.LockedException; -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.version.Version; -import org.apache.portals.graffito.jcr.version.VersionIterator; - -/** - * The persistence manager encapsulates a JCR session. - * This is the main component used to manage objects into the JCR repository. - * - * @author Sandro Boehme - * @author Lombart Christophe - * - */ -public interface PersistenceManager -{ - - /** - * Check if an object exists - * @param path the object path - * @return true if the item exists - * @throws PersistenceException when it is not possible to check if the item exist - */ - public boolean objectExists(String path) throws PersistenceException; - - - /** - * Can this persistence manager insert, update, delete, ... that type? - * - * @param clazz class for question - * @return true if the class is persistence - */ - boolean isPersistent(Class clazz); - - - /** - * Insert an object into the JCR repository - * - * @param object the object to add - * @throws PersistenceException when it is not possible to insert the object - */ - public void insert(Object object) throws PersistenceException; - - /** - * Update an object - * - * @param object the object to update - * @throws PersistenceException when it is not possible to update the object - */ - public void update(Object object) throws PersistenceException; - - /** - * Get an object from the JCR repository - * @param objectClass the object class - * @param path the object path - * @return the object found or null - * - * @throws PersistenceException when it is not possible to retrieve the object - */ - public Object getObject(Class objectClass, String path) throws PersistenceException; - - /** - * Get an object from the JCR repository - * @param objectClass the object class - * @param path the object path - * @param versionNumber The desired object version number - * @return the object found or null - * - * @throws PersistenceException when it is not possible to retrieve the object - */ - public Object getObject(Class objectClass, String path, String versionNumber) throws PersistenceException; - - - /** - * Remove an object from a JCR repository - * @param path the object path - * @throws PersistenceException when it is not possible to remove the object - * - */ - public void remove(String path) throws PersistenceException; - - - /** - * Remove an object from a JCR repository - * @param object the object to remove - * @throws PersistenceException when it is not possible to remove the object - * - */ - public void remove(Object object) throws PersistenceException; - - /** - * Remove all objects matching to a query - * @param query The query used to find the objects to remove - * @throws PersistenceException when it is not possible to remove all objects - * - */ - public void remove(Query query) throws PersistenceException; - - - /** - * Retrieve an object matching to a query - * @param query The Graffito Query object used to seach the object - * @return The object found or null - * @throws PersistenceException when it is not possible to retrieve the object - * - */ - public Object getObject(Query query) throws PersistenceException; - - - /** - * Retrieve some objects matching to a query - * @param query The query used to seach the objects - * @return a collection of objects found - * @throws PersistenceException when it is not possible to retrieve the objects - * - */ - public Collection getObjects(Query query) throws PersistenceException; - - - /** - * Retrieve some objects matching to a query. - * - * @param query The query used to seach the objects - * @return an iterator of objects found - * @throws PersistenceException when it is not possible to retrieve the objects - */ - public Iterator getObjectIterator (Query query) throws PersistenceException; - - - /** - * Checkout - Create a new version - * This is only possible if the object is based on mix:versionable node type - * - * @param path The object path - * @throws VersionException when it is not possible to create a new version - */ - public void checkout(String path) throws VersionException; - - /** - * Checkin an object - * @param path the object path - * @throws VersionException when it is not possible to checkin - */ - public void checkin(String path) throws VersionException; - - /** - * Checkin an object and apply some labels to this new version - * Within a particular object path, a given label may appear a maximum of once - * @param path The object path - * @param versionLabels the version labels to apply to the new version - * @throws VersionException when it is possible to checkin - */ - public void checkin(String path, String[] versionLabels) throws VersionException; - - - /** - * Get all version labels assigned to a particular object version - * @param path the object path - * @param versionName the object version name (1.0, ...) - * @return a array of string (version labels) - * @throws VersionException when it is not to get all version labels - */ - public String[] getVersionLabels(String path, String versionName) throws VersionException; - - - /** - * Get all version labels assigned to all versions - * @param path the object path - * @return a array of string (version labels) - * @throws VersionException when it is not to get all version labels - */ - public String[] getAllVersionLabels(String path) throws VersionException; - - /** - * Add a new label to a particular version - * @param path the object path - * @param versionName the object versio name (1.0, 1.1, ...) - * @param versionLabel The new label to apply - * @throws VersionException when it is not possible to add a new version label to this version - */ - public void addVersionLabel(String path, String versionName, String versionLabel) throws VersionException; - - - /** - * Get all object versions - * @param path the object path - * @return a version iterator - * @throws VersionException when it is not possible to retrieve all versions - */ - public VersionIterator getAllVersions(String path) throws VersionException; - - /** - * Get the first object version - * @param path the object path - * @return the first version found - * @throws VersionException when it is not possible to get the root version - */ - public Version getRootVersion(String path) throws VersionException; - - /** - * Get the lastest object version - * @param path the object path - * @return the last version found - * @throws VersionException when it is not possible to get the last version - */ - public Version getBaseVersion(String path) throws VersionException; - /** - * Get a particular version - * @param path the object path - * @param versionName the version name - * @return the version found or null - * @throws VersionException when it is not possible to retrieve this particular version - */ - public Version getVersion(String path, String versionName) throws VersionException; - - - /** - * Save all modifications made by the persistence manager - * - * @throws PersistenceException when it is not possible to save all pending operation into the JCR repo - */ - public void save() throws PersistenceException; - - /** - * Close the session - * @throws PersistenceException when it is not possible to logout - */ - public void logout() throws PersistenceException; - - /** - * Lock object saved on {@param path }. - * - * @param path - * path to saved object. - * @param isDeep - * is lock deep? See JCR spec: 8.4.3 Shallow and Deep Locks - * @param isSessionScoped - * is lock session scoped? See JCR spec: Session-scoped and Open-scoped Locks - * @return lock token - see JCR spec: 8.4.6 Lock Token; Other user with this token can perform unlock - * - * @throws LockedException - * if path is locked (cannot lock same path again) - */ - String lock(String path, boolean isDeep, boolean isSessionScoped) throws LockedException; - - /** - * Unlock object stored on {@param path }. - * - * @param path path to stored object - * - * - * @param lockToken - * see JCR spec: 8.4.6 Lock Token; can be null - * - * @throws IllegalUnlockException - * throws if the current operation does not own the current lock - */ - void unlock(String path, String lockToken) throws IllegalUnlockException; - - /** - * Is that path locked? - * - * @param absPath - * @return true if path locked - */ - boolean isLocked(String absPath); - - /** - * - * @return The query manager reference - */ - QueryManager getQueryManager(); - -} \ No newline at end of file diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/AbstractAtomicTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/AbstractAtomicTypeConverterImpl.java deleted file mode 100644 index 49e18ae3..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/AbstractAtomicTypeConverterImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter; - -/** - * Abstract implementation for {@link org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter} - * - * @author Christophe Lombart - * - */ -public abstract class AbstractAtomicTypeConverterImpl implements AtomicTypeConverter -{ - - private ValueFactory valueFactory; - - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public AbstractAtomicTypeConverterImpl() - { - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public AbstractAtomicTypeConverterImpl(ValueFactory factory) - { - super(); - valueFactory = factory; - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public abstract Value getValue(Object propValue); - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public abstract Object getObject(Value value); - - /** - * Set the JCR value factory - * - * @param valueFactory The value factory to set - */ - public void setValueFactory(ValueFactory valueFactory) - { - this.valueFactory = valueFactory; - } - - /** - * @return the JCR value factory - */ - public ValueFactory getValueFactory() - { - return this.valueFactory; - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/BinaryTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/BinaryTypeConverterImpl.java deleted file mode 100644 index d1043493..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/BinaryTypeConverterImpl.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import java.io.InputStream; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * - * Binary Type Converter - * - * @author Christophe Lombart - * - */ -public class BinaryTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public BinaryTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public BinaryTypeConverterImpl(ValueFactory factory) - { - super(factory); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - return this.getValueFactory().createValue((InputStream) propValue); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - return value.getStream(); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString() , e); - } - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - throw new IncorrectAtomicTypeException("Binary cannot be convert into string"); - } - - - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/BooleanTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/BooleanTypeConverterImpl.java deleted file mode 100644 index ffd8c169..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/BooleanTypeConverterImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * Boolean Type Converter - * - * @author Christophe Lombart - * - */ -public class BooleanTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public BooleanTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public BooleanTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - boolean value = ((Boolean) propValue).booleanValue(); - return this.getValueFactory().createValue(value); - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - return new Boolean(value.getBoolean()); - } - catch (Exception e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString() , e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return ((Boolean) object).booleanValue() ? "true()" : "false()"; - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/ByteArrayTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/ByteArrayTypeConverterImpl.java deleted file mode 100644 index 0edd5c84..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/ByteArrayTypeConverterImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * - * Byte Array Type Converter - * - * @author Christophe Lombart - * - */ -public class ByteArrayTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public ByteArrayTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public ByteArrayTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - String value = new String((byte[]) propValue); - return getValueFactory().createValue(value); - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - return value.getString().getBytes(); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString() , e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return "'" + object.toString() + "'"; - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/CalendarTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/CalendarTypeConverterImpl.java deleted file mode 100644 index 2377ce8a..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/CalendarTypeConverterImpl.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import java.util.Calendar; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * Calendar Type Converter - * - * @author Christophe Lombart - * - */ -public class CalendarTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public CalendarTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public CalendarTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - return this.getValueFactory().createValue(((Calendar) propValue).getTimeInMillis()); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(value.getLong()); - return calendar; - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - Calendar calendar = (Calendar) object; - return new Long(calendar.getTimeInMillis()).toString(); - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/DoubleTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/DoubleTypeConverterImpl.java deleted file mode 100644 index 1d308b63..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/DoubleTypeConverterImpl.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * Double Type Converter - * - * @author Christophe Lombart - * - */ -public class DoubleTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public DoubleTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - - public DoubleTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - double value = ((Double) propValue).doubleValue(); - return this.getValueFactory().createValue(value); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - double beanPropValue = value.getDouble(); - return new Double(beanPropValue); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return object.toString(); - } - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/IntTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/IntTypeConverterImpl.java deleted file mode 100644 index 8f27e6be..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/IntTypeConverterImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * Int Type Converter - * - * @author Christophe Lombart - * - */ -public class IntTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public IntTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public IntTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - long value = ((Integer) propValue).intValue(); - return this.getValueFactory().createValue(value); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - int beanPropValue = (int) value.getLong(); - return new Integer(beanPropValue); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return object.toString(); - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/LongTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/LongTypeConverterImpl.java deleted file mode 100644 index 3b4c8c38..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/LongTypeConverterImpl.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * - * Long Type Converter - * - * @author Christophe Lombart - * - */ -public class LongTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public LongTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public LongTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - - long value = ((Long) propValue).longValue(); - return this.getValueFactory().createValue(value); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - long beanPropValue = value.getLong(); - return new Long(beanPropValue); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return object.toString(); - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/StringTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/StringTypeConverterImpl.java deleted file mode 100644 index d9a75852..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/StringTypeConverterImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * - * String Type Converter - * - * @author Christophe Lombart - * - */ -public class StringTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public StringTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public StringTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - return this.getValueFactory().createValue((String) propValue); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - return value.getString(); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return "'" + object.toString() + "'"; - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/TimestampTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/TimestampTypeConverterImpl.java deleted file mode 100644 index 1475bcbe..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/TimestampTypeConverterImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import java.sql.Timestamp; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * - * Timestamp Type Converter - * - * @author Christophe Lombart - * - */ -public class TimestampTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public TimestampTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public TimestampTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - return null; - long value = ((Timestamp) propValue).getTime(); - return this.getValueFactory().createValue(value); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - long beanPropValue = value.getLong(); - return new Timestamp(beanPropValue); - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return new Long(((Timestamp) object).getTime()).toString(); - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/UtilDateTypeConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/UtilDateTypeConverterImpl.java deleted file mode 100644 index af474ad8..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/impl/UtilDateTypeConverterImpl.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl; - -import java.util.Date; - -import javax.jcr.RepositoryException; -import javax.jcr.Value; -import javax.jcr.ValueFactory; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - -/** - * Util Date Converter - * - * @author Christophe Lombart - * - */ -public class UtilDateTypeConverterImpl extends AbstractAtomicTypeConverterImpl -{ - /** - * No-arg constructor. - * When using it you should provide later the javax.jcr.ValueFactory. - * - * @see #setValueFactory(ValueFactory) - */ - public UtilDateTypeConverterImpl() - { - super(); - } - - /** - * Constructor - * @param factory The JCR Value factory to used - */ - public UtilDateTypeConverterImpl(ValueFactory factory) - { - super(factory); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) - */ - public Value getValue(Object propValue) - { - if (propValue == null) - { - return null; - } - return this.getValueFactory().createValue(((java.util.Date) propValue).getTime()); - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) - */ - public Object getObject(Value value) - { - try - { - long time = value.getLong(); - return new Date(time); - - } - catch (RepositoryException e) - { - throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) - */ - public String getStringValue(Object object) - { - - return new Long(((java.util.Date) object).getTime()).toString(); - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/CollectionConverter.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/CollectionConverter.java deleted file mode 100644 index 3add79c1..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/CollectionConverter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence.collectionconverter; - -import javax.jcr.Node; -import javax.jcr.Session; - -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor; - -/** - * Convert any kind of {@link ManageableCollection} into severals JCR nodes. - * - * @author Lombart Christophe - * - */ -public interface CollectionConverter -{ - - /** - * Insert/convert collection elements into some JCR nodes - * @param session The JCR session - * @param parentNode the node which will contains the collection element - * @param collectionDescriptor The collection descriptor - * @param collection the collection to insert - * - * @throws PersistenceException when it is not possible to insert the collection - * - */ - public void insertCollection(Session session, Node parentNode, - CollectionDescriptor collectionDescriptor, ManageableCollection collection) throws PersistenceException; - - /** - * Update collection elements already present in the JCR repository - * @param session The JCR session - * @param parentNode the node which will contains the collection element - * @param collectionDescriptor The collection descriptor - * @param collection the collection to update - * - * @throws PersistenceException when it is not possible to update the collection - */ - public void updateCollection(Session session, Node parentNode, - CollectionDescriptor collectionDescriptor, ManageableCollection collection) throws PersistenceException; - - /** - * Get a {@link ManageableCollection} from the JCR repository - * @param session The JCR session - * @param parentNode the node which contains the collection element - * @param collectionDescriptor The collection descriptor - * @param collectionFieldClass The collection class to used (ArrayList, Vector, ..) - * @return The collection populates with all elements found in the JCR repository - * - * @throws PersistenceException when it is not possible to retrieve the collection - */ - public ManageableCollection getCollection(Session session, Node parentNode, - CollectionDescriptor collectionDescriptor, Class collectionFieldClass) throws PersistenceException; - -} \ No newline at end of file diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/ManageableCollectionUtil.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/ManageableCollectionUtil.java deleted file mode 100644 index 00c93658..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/ManageableCollectionUtil.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence.collectionconverter; - - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Vector; - -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.impl.ManageableArrayList; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.impl.ManageableVector; - -/** - * Utility class used to instantiate {@link ManageableCollection} - * - * @author Christophe Lombart - * - */ -public class ManageableCollectionUtil -{ - - /** - * Instantiate a new {@link ManageableCollection} - * @param manageableCollectionClassName The manageable collection class name - * @return an emtpy created {@link ManageableCollection} - */ - public static ManageableCollection getManageableCollection(String manageableCollectionClassName) - { - try - { - Class collectionClass = Class.forName(manageableCollectionClassName); - return (ManageableCollection) collectionClass.newInstance(); - } - catch (Exception e) - { - throw new PersistenceException("Impossible to create the manageable collection : " + manageableCollectionClassName, e); - } - } - - /** - * Instantiate a new {@link ManageableCollection} - * @param collectionClass the collection class name - * @return an emtpy created {@link ManageableCollection} - */ - - public static ManageableCollection getManageableCollection(Class collectionClass) - { - try - { - - if (collectionClass.equals(ArrayList.class)) - { - return new ManageableArrayList(); - } - - if (collectionClass.equals(Vector.class)) - { - return new ManageableVector(); - } - - if (collectionClass.equals(Collection.class) || collectionClass.equals(List.class)) - { - return new ManageableArrayList(); - } - - Object collection = collectionClass.newInstance(); - if (! (collection instanceof ManageableCollection)) - { - throw new PersistenceException("Unsupported collection type :" + collectionClass.getName()); - } - else - { - return (ManageableCollection) collection; - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to create the manageable collection", e); - } - } - - /** - * Convert a java Collection object into a {@link ManageableCollection}. - * Until now, only the following class are supported : - * Collection, List, ArrayList, Vector - * - * If you need a Map, you have to write your own {@link ManageableCollection}. - * @param object the java collection or Map - * @return The converted {@link ManageableCollection} - * - */ - public static ManageableCollection getManageableCollection(Object object) - { - try - { - if (object == null) - { - return null; - } - - if (object instanceof ManageableCollection) - { - return (ManageableCollection) object; - - } - if (object.getClass().equals(ArrayList.class)) - { - ManageableArrayList manageableArrayList = new ManageableArrayList(); - manageableArrayList.addAll((Collection) object); - return manageableArrayList; - } - - if (object.getClass().equals(Vector.class)) - { - ManageableVector manageableVector = new ManageableVector(); - manageableVector.addAll((Collection) object); - return manageableVector; - } - - if (object.getClass().equals(Collection.class) || object.getClass().equals(List.class)) - { - ManageableArrayList manageableArrayList = new ManageableArrayList(); - manageableArrayList.addAll((Collection) object); - return manageableArrayList; - } - - throw new PersistenceException("Unsupported collection type :" + object.getClass().getName()); - } - catch (Exception e) - { - throw new PersistenceException("Impossible to create the manageable collection", e); - } - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/AbstractCollectionConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/AbstractCollectionConverterImpl.java deleted file mode 100644 index 982c05c0..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/AbstractCollectionConverterImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; - -import java.util.Map; - -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter; -import org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter; - -/** - * Abstract class used for all CollectionConverter - * - * @author Christophe Lombart - * - */ -public abstract class AbstractCollectionConverterImpl implements CollectionConverter -{ - protected Map atomicTypeConverters; - protected ObjectConverter objectConverter; - protected Mapper mapper; - - /** - * Constructor - * - * @param atomicTypeConverters The atomic type converter to used - * @param objectConverter The object converter to used - * @param mapper The mapper to used - */ - public AbstractCollectionConverterImpl(Map atomicTypeConverters, ObjectConverter objectConverter, Mapper mapper) - { - this.atomicTypeConverters = atomicTypeConverters; - this.objectConverter = objectConverter; - this.mapper = mapper; - } - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/DefaultCollectionConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/DefaultCollectionConverterImpl.java deleted file mode 100644 index 1caecfb7..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/DefaultCollectionConverterImpl.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.jcr.Node; -import javax.jcr.NodeIterator; -import javax.jcr.Session; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollectionUtil; -import org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter; - -/** - * Default Collection Mapping/convertion implementation. - * - * This collection mapping strategy maps a collection under an extra JCR node (specify by the jcrName in the CollectionDescriptor). - * It is usefull when the node type "nt:unstructured" is applied to the collection elements. By this way, it is possible - * to distinguish the collection elements from the other main object fields. - * - * If the collection element class contains an id (see the FieldDescriptor definition), this id value is used to build the collection element node. - * Otherwise, the element node name is a simple indexed constant. - * - * Example - without an id attribute: - * /test (Main object containing the collection field ) - * /mycollection (extra node used to store the entire collection) - * /collection-element1 (node used to store the first collection element) - * /item-prop - * .... - * /collection-element2 (node used to store the second collection element) - * ... - * - * Example - with an id attribute: - * /test (Main object containing the collection field ) - * /mycollection (extra node used to store the entire collection) - * /aValue (id value assigned to the first element) - * /item-prop - * .... - * /anotherValue (id value assigned to the first element) - * ... - - * @author Christophe Lombart - * - */ -public class DefaultCollectionConverterImpl extends AbstractCollectionConverterImpl -{ - - private static final String COLLECTION_ELEMENT_NAME = "collection-element"; - - /** - * Constructor - * @param atomicTypeConverters - * @param objectConverter - * @param mapper - */ - public DefaultCollectionConverterImpl(Map atomicTypeConverters, ObjectConverter objectConverter, Mapper mapper) - { - super(atomicTypeConverters, objectConverter, mapper); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#insertCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection) - */ - public void insertCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) - { - - try - { - - if (collection == null) - { - return; - } - - String jcrName = collectionDescriptor.getJcrName(); - - if (jcrName == null) - { - throw new PersistenceException("The JcrName attribute is not defined for the CollectionDescriptor : " - + collectionDescriptor.getCollectionConverterClassName()); - } - - Node collectionNode = parentNode.addNode(jcrName); - - Iterator collectionIterator = collection.getIterator(); - ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor(Class.forName(collectionDescriptor - .getElementClassName())); - - int elementCollectionCount = 0; - while (collectionIterator.hasNext()) - { - Object item = collectionIterator.next(); - String elementJcrName = null; - - // If the element object has a unique id => the element jcr node name = the id value - if (elementClassDescriptor.hasIdField()) - { - String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); - elementJcrName = PropertyUtils.getNestedProperty(item, idFieldName).toString(); - } - else - { - - elementCollectionCount++; - elementJcrName = COLLECTION_ELEMENT_NAME + elementCollectionCount; - } - - objectConverter.insert(session, collectionNode, elementJcrName, item); - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to insert the collection field : " + collectionDescriptor.getFieldName() - + "for " + collectionDescriptor.getElementClassName(), e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#updateCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection) - */ - public void updateCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) - { - try - { - - String jcrName = collectionDescriptor.getJcrName(); - - if (jcrName == null) - { - throw new PersistenceException("The JcrName attribute is not defined for the CollectionDescriptor : " - + collectionDescriptor.getCollectionConverterClassName()); - } - - if (collection == null) - { - if (parentNode.hasNode(jcrName)) - { - parentNode.getNode(jcrName).remove(); - - } - return; - } - - Node collectionNode = parentNode.getNode(jcrName); - ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor(Class.forName(collectionDescriptor - .getElementClassName())); - Iterator collectionIterator = collection.getIterator(); - int elementCollectionCount = 0; - - // If the collection elements have not an id, it is not possible to find the matching JCR nodes => delete the complete collection - if (!elementClassDescriptor.hasIdField()) - { - collectionNode.remove(); - collectionNode = parentNode.addNode(jcrName); - } - - HashMap updatedItems = new HashMap(); - while (collectionIterator.hasNext()) - { - Object item = collectionIterator.next(); - - elementCollectionCount++; - String elementJcrName = null; - - if (elementClassDescriptor.hasIdField()) - { - - String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); - elementJcrName = PropertyUtils.getNestedProperty(item, idFieldName).toString(); - - // Update existing JCR Nodes - if (collectionNode.hasNode(elementJcrName)) - { - objectConverter.update(session, collectionNode, elementJcrName, item); - } - else - { - // Add new collection elements - objectConverter.insert(session, collectionNode, elementJcrName, item); - } - - updatedItems.put(elementJcrName, item); - - } - else - { - - elementCollectionCount++; - elementJcrName = COLLECTION_ELEMENT_NAME + elementCollectionCount; - objectConverter.insert(session, collectionNode, elementJcrName, item); - } - - } - - // Delete JCR nodes that are not present in the collection - if (elementClassDescriptor.hasIdField()) - { - NodeIterator nodeIterator = collectionNode.getNodes(); - while (nodeIterator.hasNext()) - { - Node child = nodeIterator.nextNode(); - if (! updatedItems.containsKey(child.getName())) - { - child.remove(); - } - } - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to update the collection field : " + collectionDescriptor.getFieldName() - + "for " + collectionDescriptor.getElementClassName(), e); - } - - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#getCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, java.lang.Class) - */ - public ManageableCollection getCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, Class collectionFieldClass) - { - try - { - String jcrName = collectionDescriptor.getJcrName(); - if (!parentNode.hasNode(jcrName)) - { - return null; - } - - Node collectionNode = parentNode.getNode(jcrName); - NodeIterator children = collectionNode.getNodes(); - - ManageableCollection collection = ManageableCollectionUtil.getManageableCollection(collectionFieldClass); - - while (children.hasNext()) - { - Node itemNode = children.nextNode(); - Object item = objectConverter.getObject(session, Class.forName(collectionDescriptor.getElementClassName()), - itemNode.getPath()); - collection.addObject(item); - } - - return collection; - } - catch (Exception e) - { - throw new PersistenceException("Impossible to get the collection field : " + collectionDescriptor.getFieldName() - + "for " + collectionDescriptor.getElementClassName(), e); - } - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/ManageableArrayList.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/ManageableArrayList.java deleted file mode 100644 index 42be80f5..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/ManageableArrayList.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection; - -/** - * - * {@link ManageableCollection} ArrayList implementation - * - * @author Christophe Lombart - * - */ -public class ManageableArrayList extends ArrayList implements ManageableCollection -{ - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#addObject(java.lang.Object) - */ - public void addObject(Object object) - { - this.add(object); - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#getIterator() - */ - public Iterator getIterator() - { - return this.iterator(); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#getSize() - */ - public int getSize() - { - - return this.size(); - } - - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/ManageableVector.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/ManageableVector.java deleted file mode 100644 index 13afbfaa..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/ManageableVector.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; - -import java.util.Iterator; -import java.util.Vector; - -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection; - -/** - * - * {@link ManageableCollection} Vector implementation - * @author Christophe Lombart - * - */ -public class ManageableVector extends Vector implements ManageableCollection -{ - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#addObject(java.lang.Object) - */ - public void addObject(Object object) - { - this.add(object); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#getIterator() - */ - public Iterator getIterator() - { - return this.iterator(); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#getSize() - */ - public int getSize() - { - - return this.size(); - } - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/MultiValueCollectionConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/MultiValueCollectionConverterImpl.java deleted file mode 100644 index 33e34db3..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/MultiValueCollectionConverterImpl.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; - -import java.util.Iterator; -import java.util.Map; - -import javax.jcr.Node; -import javax.jcr.Property; -import javax.jcr.Session; -import javax.jcr.Value; - -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollectionUtil; -import org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter; - -/** - * Collection Mapping/convertion implementation used for multi values properties - * - * This collection mapping strategy maps a collection into a JCR multi value property - * - * @author Christophe Lombart - * - */ -public class MultiValueCollectionConverterImpl extends AbstractCollectionConverterImpl -{ - /** - * Constructor - * - * @param atomicTypeConverters - * @param objectConverter - * @param mapper - */ - public MultiValueCollectionConverterImpl(Map atomicTypeConverters, ObjectConverter objectConverter, Mapper mapper) - { - super(atomicTypeConverters, objectConverter, mapper); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#insertCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection) - */ - public void insertCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) - { - - try - { - - if (collection == null) - { - return; - } - - String jcrName = collectionDescriptor.getJcrName(); - - if (jcrName == null) - { - throw new PersistenceException("The JcrName attribute is not defined for the CollectionDescriptor : " - + collectionDescriptor.getCollectionConverterClassName()); - } - - Value[] values = new Value[collection.getSize()]; - Iterator collectionIterator = collection.getIterator(); - for (int i=0; iChristophe Lombart - * - */ -public class NTCollectionConverterImpl extends AbstractCollectionConverterImpl -{ - - private final static Log log = LogFactory.getLog(NTCollectionConverterImpl.class); - - private static final String COLLECTION_ELEMENT_NAME = "collection-element"; - - /** - * Constructor - * - * @param atomicTypeConverters - * @param objectConverter - * @param mapper - */ - public NTCollectionConverterImpl(Map atomicTypeConverters, ObjectConverter objectConverter, Mapper mapper) - { - super(atomicTypeConverters, objectConverter, mapper); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#insertCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection) - */ - public void insertCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) - { - - try - { - - if (collection == null) - { - return; - } - - - Iterator collectionIterator = collection.getIterator(); - ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor(Class.forName(collectionDescriptor - .getElementClassName())); - - int elementCollectionCount = 0; - while (collectionIterator.hasNext()) - { - Object item = collectionIterator.next(); - String elementJcrName = null; - - // If the element object has a unique id => the element jcr node name = the id value - if (elementClassDescriptor.hasIdField()) - { - String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); - elementJcrName = PropertyUtils.getNestedProperty(item, idFieldName).toString(); - } - else - { - - elementCollectionCount++; - elementJcrName = COLLECTION_ELEMENT_NAME + elementCollectionCount; - } - - objectConverter.insert(session, parentNode, elementJcrName, item); - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to insert the collection field : " + collectionDescriptor.getFieldName() - + "for " + collectionDescriptor.getElementClassName(), e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#updateCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection) - */ - public void updateCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, ManageableCollection collection) - { - try - { - - ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor(Class.forName(collectionDescriptor - .getElementClassName())); - - if (collection == null) - { - this.deleteCollectionItems(session, parentNode, elementClassDescriptor.getJcrNodeType()); - return; - } - - if (!elementClassDescriptor.hasIdField()) - { - this.deleteCollectionItems(session, parentNode, elementClassDescriptor.getJcrNodeType()); - } - - Iterator collectionIterator = collection.getIterator(); - int elementCollectionCount = 0; - - HashMap updatedItems = new HashMap(); - while (collectionIterator.hasNext()) - { - Object item = collectionIterator.next(); - - elementCollectionCount++; - String elementJcrName = null; - - if (elementClassDescriptor.hasIdField()) - { - - String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); - elementJcrName = PropertyUtils.getNestedProperty(item, idFieldName).toString(); - - // Update existing JCR Nodes - if (parentNode.hasNode(elementJcrName)) - { - objectConverter.update(session, parentNode, elementJcrName, item); - } - else - { - // Add new collection elements - objectConverter.insert(session, parentNode, elementJcrName, item); - } - - updatedItems.put(elementJcrName, item); - - } - else - { - - elementJcrName = COLLECTION_ELEMENT_NAME + elementCollectionCount; - objectConverter.insert(session, parentNode, elementJcrName, item); - } - - } - - // Delete JCR nodes that are not present in the collection - if (elementClassDescriptor.hasIdField()) - { - Iterator nodeIterator = this.getCollectionNodes(session, parentNode, elementClassDescriptor.getJcrNodeType()).iterator(); - while (nodeIterator.hasNext()) - { - Node child = (Node) nodeIterator.next(); - if (! updatedItems.containsKey(child.getName())) - { - child.remove(); - } - } - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to update the collection field : " + collectionDescriptor.getFieldName() - + "for " + collectionDescriptor.getElementClassName(), e); - } - - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter#getCollection(javax.jcr.Session, javax.jcr.Node, org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor, java.lang.Class) - */ - public ManageableCollection getCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, Class collectionFieldClass) - { - try - { - ClassDescriptor elementClassDescriptor = mapper.getClassDescriptor(Class.forName(collectionDescriptor - .getElementClassName())); - Iterator children = this.getCollectionNodes(session, parentNode, elementClassDescriptor.getJcrNodeType()).iterator(); - - ManageableCollection collection = ManageableCollectionUtil.getManageableCollection(collectionFieldClass); - - while (children.hasNext()) - { - Node itemNode = (Node) children.next(); - log.debug("Collection node found : " + itemNode.getPath()); - Object item = objectConverter.getObject(session, Class.forName(collectionDescriptor.getElementClassName()), - itemNode.getPath()); - collection.addObject(item); - } - - return collection; - } - catch (Exception e) - { - throw new PersistenceException("Impossible to get the collection field : " + collectionDescriptor.getFieldName() - + "for " + collectionDescriptor.getElementClassName(), e); - } - } - - private Collection getCollectionNodes (Session session, Node parentNode, String itemNodeType) throws Exception - { - - ArrayList collectionNodes = new ArrayList(); - - // TODO : review this workaround used to support version nodes - // Searching on the version storage has some bugs => loop on all child noded and check the property jcr:frozenPrimaryType - // I have to investigate in more detail what's happen exactly - if (! parentNode.getPath().startsWith("/jcr:system/jcr:versionStorage")) - { - NodeIterator nodeIterator = parentNode.getNodes(); - while (nodeIterator.hasNext()) - { - Node child = nodeIterator.nextNode(); - - if (child.isNodeType(itemNodeType)) - { - collectionNodes.add(child); - } - } - } - else - { - - NodeIterator nodeIterator = parentNode.getNodes(); - while (nodeIterator.hasNext()) - { - Node child = nodeIterator.nextNode(); - - if (child.getProperty("jcr:frozenPrimaryType").getString().equals(itemNodeType)) - { - collectionNodes.add(child); - } - } - - } - - return collectionNodes; - - } - - private void deleteCollectionItems(Session session, Node parentNode, String itemNodeType) throws Exception - { - Iterator nodeIterator = this.getCollectionNodes(session, parentNode, itemNodeType).iterator(); - while (nodeIterator.hasNext()) - { - Node node = (Node) nodeIterator.next(); - node.remove(); - } - } - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/impl/ObjectIterator.java b/src/java/org/apache/portals/graffito/jcr/persistence/impl/ObjectIterator.java deleted file mode 100644 index c0e7f5c1..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/impl/ObjectIterator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.util.Iterator; - -import javax.jcr.Node; -import javax.jcr.NodeIterator; -import javax.jcr.Session; - -import org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter; - - -/** - * ObjectIterator is a wrapper class for JCR NodeIterator - * - * @author Christophe Lombart - * - */ -public class ObjectIterator implements Iterator -{ - - private NodeIterator nodeIterator; - - private Class objectClass; - - private Session session; - - private ObjectConverter objectConverter; - - - /** - * Constructor - * - * @param iterator JCR node iterator - * @param objectClass the object class used to instantiate the objects - * @param converter The object converter - * @param session the JCR session - */ - public ObjectIterator(NodeIterator iterator, Class objectClass, ObjectConverter converter, Session session) - { - nodeIterator = iterator; - this.objectClass = objectClass; - objectConverter = converter; - this.session = session; - } - - /** - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() - { - return nodeIterator.hasNext(); - } - - /** - * - * @see java.util.Iterator#next() - */ - public Object next() - { - - try - { - Node node = nodeIterator.nextNode(); - return objectConverter.getObject(session, objectClass, node.getPath()); - } - catch (Exception e) - { - return null; - } - - } - - /** - * - * @see java.util.Iterator#remove() - */ - public void remove() - { - nodeIterator.remove(); - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerImpl.java deleted file mode 100644 index 0f1facc6..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerImpl.java +++ /dev/null @@ -1,910 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; - -import javax.jcr.Item; -import javax.jcr.Node; -import javax.jcr.NodeIterator; -import javax.jcr.PathNotFoundException; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.lock.Lock; -import javax.jcr.lock.LockException; -import javax.jcr.query.QueryResult; -import javax.jcr.version.VersionHistory; - -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.exception.IllegalUnlockException; -import org.apache.portals.graffito.jcr.exception.JcrMappingException; -import org.apache.portals.graffito.jcr.exception.LockedException; -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.exception.VersionException; -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter; -import org.apache.portals.graffito.jcr.persistence.objectconverter.impl.ObjectConverterImpl; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.version.Version; -import org.apache.portals.graffito.jcr.version.VersionIterator; - -/** - * - * Default implementation for {@link org.apache.portals.graffito.jcr.persistence.PersistenceManager} - * - * @author Sandro Boehme - * @author Lombart Christophe - * @author Martin Koci - * - */ -public class PersistenceManagerImpl implements PersistenceManager -{ - /** - * Logger. - */ - private final static Log log = LogFactory - .getLog(PersistenceManagerImpl.class); - - /** - * JCR session. - */ - protected Session session; - - protected Mapper mapper; - - /** - * The Graffito query manager - */ - protected QueryManager queryManager; - - /** - * Object Converter - */ - protected ObjectConverter objectConverter; - - /** - * Contructor - * - * @param mapper the Mapper component - * @param atomicTypeConverters Atomic type converters to used - * @param queryManager the query manager to used - * @param session The JCR session - * - */ - public PersistenceManagerImpl(Mapper mapper, Map atomicTypeConverters, - QueryManager queryManager, Session session) - { - this.mapper = mapper; - this.session = session; - this.objectConverter = new ObjectConverterImpl(mapper, - atomicTypeConverters); - this.queryManager = queryManager; - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getObject(java.lang.Class, java.lang.String) - */ - public Object getObject(Class objectClass, String path) - { - try - { - if (!session.itemExists(path)) - { - return null; - } - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to get the object at " - + path, e); - } - - return objectConverter.getObject(session, objectClass, path); - - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getObject(java.lang.Class, java.lang.String, java.lang.String) - */ - public Object getObject(Class objectClass, String path, String versionName) - throws PersistenceException - { - String pathVersion = null; - try - { - if (!session.itemExists(path)) - { - return null; - } - - Version version = this.getVersion(path, versionName); - pathVersion = version.getPath() + "/jcr:frozenNode"; - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to get the object at " - + path + " - version :" + versionName, e); - } - - return objectConverter.getObject(session, objectClass, pathVersion); - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#insert(java.lang.Object) - */ - public void insert(Object object) - { - String path = objectConverter.getPath(session, object); - - try - { - - if (session.itemExists(path)) - { - Item item = session.getItem(path); - if (item.isNode()) - { - if (!((Node) item).getDefinition().allowsSameNameSiblings()) - { - throw new PersistenceException( - "Path already exists and it is not supporting the same name sibling : " - + path); - } - } - else - { - throw new PersistenceException( - "Path already exists and it is a property : " - + path); - } - - } - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to insert the object at " + path, e); - } - - objectConverter.insert(session, object); - - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#update(java.lang.Object) - */ - public void update(Object object) - { - String path = objectConverter.getPath(session, object); - try - { - if (!session.itemExists(path)) - { - throw new PersistenceException("Path is not existing : " + path); - } - else - { - checkIfNodeLocked(path); - } - } - catch (RepositoryException e) - { - throw new PersistenceException("Impossible to update", e); - } - - objectConverter.update(session, object); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#remove(java.lang.String) - */ - public void remove(String path) - { - - try - { - if (!session.itemExists(path)) - { - throw new PersistenceException("Path is not existing : " + path); - } - else - { - checkIfNodeLocked(path); - } - - Item item = session.getItem(path); - item.remove(); - - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to remove the object at " + path); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#remove(java.lang.Object) - */ - public void remove(Object object) throws PersistenceException - { - this.remove(objectConverter.getPath(session, object)); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#remove(org.apache.portals.graffito.jcr.query.Query) - */ - public void remove(Query query) - { - try - { - - String jcrExpression = this.queryManager.buildJCRExpression(query); - log.debug("Remove Objects with expression : " + jcrExpression); - - javax.jcr.query.Query jcrQuery = session.getWorkspace().getQueryManager().createQuery(jcrExpression,javax.jcr.query.Query.XPATH); - QueryResult queryResult = jcrQuery.execute(); - NodeIterator nodeIterator = queryResult.getNodes(); - ArrayList nodes = new ArrayList(); - - while (nodeIterator.hasNext()) - { - Node node = nodeIterator.nextNode(); - log.debug("Remove node : " + node.getPath()); - // it is not possible to remove nodes from an NodeIterator - // So, we add the node found in a collection to remove them after - nodes.add(node); - } - - // Remove all collection nodes - for (int i = 0; i < nodes.size(); i++) - { - Node node = (Node) nodes.get(i); - checkIfNodeLocked(node.getPath()); - node.remove(); - } - - } - catch (RepositoryException e) - { - throw new PersistenceException("Impossible to get the object collection", e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#objectExists(java.lang.String) - */ - public boolean objectExists(String path) - { - try - { - //TODO : Check also if it is an object - return session.itemExists(path); - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to check if the object exist", e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#isPersistent(java.lang.Class) - */ - public boolean isPersistent(final Class clazz) - { - boolean isPersistent = false; - ClassDescriptor classDescriptor = mapper.getClassDescriptor(clazz); - if (classDescriptor != null) - { - isPersistent = true; - } - return isPersistent; - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getObject(org.apache.portals.graffito.jcr.query.Query) - */ - public Object getObject(Query query) - { - - try - { - - String jcrExpression = this.queryManager.buildJCRExpression(query); - log.debug("Get Object with expression : " + jcrExpression); - - javax.jcr.query.Query jcrQuery = session.getWorkspace() - .getQueryManager().createQuery(jcrExpression, - javax.jcr.query.Query.XPATH); - QueryResult queryResult = jcrQuery.execute(); - NodeIterator nodeIterator = queryResult.getNodes(); - - if (nodeIterator.getSize() > 1) - { - throw new PersistenceException( - "Impossible to get the object - the query returns more than one object"); - } - - Object object = null; - if (nodeIterator.hasNext()) - { - Node node = nodeIterator.nextNode(); - object = objectConverter.getObject(session, query.getFilter() - .getFilterClass(), node.getPath()); - } - - return object; - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the object collection", e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getObjects(org.apache.portals.graffito.jcr.query.Query) - */ - public Collection getObjects(Query query) - { - try - { - - String jcrExpression = this.queryManager.buildJCRExpression(query); - log.debug("Get Objects with expression : " + jcrExpression); - - javax.jcr.query.Query jcrQuery = session.getWorkspace() - .getQueryManager().createQuery(jcrExpression, - javax.jcr.query.Query.XPATH); - QueryResult queryResult = jcrQuery.execute(); - NodeIterator nodeIterator = queryResult.getNodes(); - - ArrayList result = new ArrayList(); - while (nodeIterator.hasNext()) - { - Node node = nodeIterator.nextNode(); - log.debug("Node found : " + node.getPath()); - result.add(objectConverter.getObject(session, query.getFilter() - .getFilterClass(), node.getPath())); - } - - return result; - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the object collection", e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getObjectIterator(org.apache.portals.graffito.jcr.query.Query) - */ - public Iterator getObjectIterator(Query query) - { - try - { - - String jcrExpression = this.queryManager.buildJCRExpression(query); - log.debug("Get Object with expression : " + jcrExpression); - - javax.jcr.query.Query jcrQuery = session.getWorkspace() - .getQueryManager().createQuery(jcrExpression, - javax.jcr.query.Query.XPATH); - QueryResult queryResult = jcrQuery.execute(); - NodeIterator nodeIterator = queryResult.getNodes(); - return new ObjectIterator(nodeIterator, query.getFilter() - .getFilterClass(), this.objectConverter, this.session); - - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the object collection", e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#checkin(java.lang.String) - */ - public void checkin(String path) - { - this.checkin(path, null); - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#checkin(java.lang.String, java.lang.String[]) - */ - public void checkin(String path, String[] versionLabels) - { - try - { - Node node = (Node) session.getItem(path); - checkIfNodeLocked(node.getPath()); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - javax.jcr.version.Version newVersion = node.checkin(); - - if (versionLabels != null) - { - VersionHistory versionHistory = node.getVersionHistory(); - for (int i = 0; i < versionLabels.length; i++) - { - versionHistory.addVersionLabel(newVersion.getName(), - versionLabels[i], false); - } - } - } - catch (RepositoryException e) - { - throw new VersionException("Impossible to checkin the object " - + path, e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#checkout(java.lang.String) - */ - public void checkout(String path) - { - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - node.checkout(); - - } - catch (RepositoryException e) - { - throw new VersionException("Impossible to checkout the object " - + path, e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#addVersionLabel(java.lang.String, java.lang.String, java.lang.String) - */ - public void addVersionLabel(String path, String versionName, - String versionLabel) - { - try - { - Node node = (Node) session.getItem(path); - checkIfNodeLocked(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - VersionHistory history = node.getVersionHistory(); - history.addVersionLabel(versionName, versionLabel, false); - } - catch (RepositoryException e) - { - throw new VersionException( - "Impossible to add a new version label to " + path - + " - version name : " + versionName, e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getVersion(java.lang.String, java.lang.String) - */ - public Version getVersion(String path, String versionName) - { - - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - VersionHistory history = node.getVersionHistory(); - - return new Version(history.getVersion(versionName)); - } - catch (RepositoryException e) - { - throw new PersistenceException("Impossible to get the version : " - + path + " - version name : " + versionName, e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getVersionLabels(java.lang.String, java.lang.String) - */ - public String[] getVersionLabels(String path, String versionName) - { - - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - VersionHistory history = node.getVersionHistory(); - javax.jcr.version.Version version = history.getVersion(versionName); - return history.getVersionLabels(version); - - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the version labels : " + path - + " - version name : " + versionName, e); - } - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getAllVersionLabels(java.lang.String) - */ - public String[] getAllVersionLabels(String path) - throws javax.jcr.version.VersionException - { - - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - VersionHistory history = node.getVersionHistory(); - return history.getVersionLabels(); - - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the all version labels : " + path, e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getAllVersions(java.lang.String) - */ - public VersionIterator getAllVersions(String path) - { - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - VersionHistory history = node.getVersionHistory(); - return new VersionIterator(history.getAllVersions()); - } - catch (RepositoryException e) - { - throw new PersistenceException("Impossible to checkin the object " - + path, e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getRootVersion(java.lang.String) - */ - public Version getRootVersion(String path) - { - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - VersionHistory history = node.getVersionHistory(); - - return new Version(history.getRootVersion()); - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the root version for the object " - + path, e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getBaseVersion(java.lang.String) - */ - public Version getBaseVersion(String path) - { - try - { - Node node = (Node) session.getItem(path); - if (!node.isNodeType("mix:versionable")) - { - throw new VersionException("The object " + path - + "is not versionable"); - } - - return new Version(node.getBaseVersion()); - } - catch (RepositoryException e) - { - throw new PersistenceException( - "Impossible to get the base version for the object " + path, - e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#lock(java.lang.String, java.lang.Object, boolean, boolean) - */ - public String lock(final String absPath, final boolean isDeep, final boolean isSessionScoped) throws LockedException - { - try - { - - // Calling this method will throw exception if node is locked - // and this operation cant be done (exception translation) - checkIfNodeLocked(absPath); - - Node node = getNode(absPath); - Lock lock = node.lock(isDeep, isSessionScoped); - return lock.getLockToken(); - } - catch (LockException e) - { - // Only one case with LockException remains: if node is not mix:lockable, propably error in custom node types definitions - throw new org.apache.portals.graffito.jcr.exception.RepositoryException("Node of type is not type mix:lockable", e); - } - catch (RepositoryException e) - { - throw new org.apache.portals.graffito.jcr.exception.RepositoryException(e.getMessage(), e); - } - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#unlock(java.lang.String, java.lang.Object, java.lang.String) - */ - public void unlock(final String absPath, final String lockToken) throws JcrMappingException, IllegalUnlockException - { - Node node; - Lock lock; - String lockOwner = null; - try - { - maybeAddLockToken(lockToken); - - node = getNode(absPath); - - if (node.isLocked() == false) - { - // Safe - if not locked return - return; - } - - lock = node.getLock(); - lockOwner = lock.getLockOwner(); - - node.unlock(); - } - catch (LockException e) - { - // LockException if this node does not currently hold a lock (see upper code) - // or holds a lock for which this Session does not have the correct lock token - log.error("Cannot unlock path: " - + absPath - + " Jcr user: " - + session.getUserID() - + " has no lock token to do this. Lock was placed with user: " - + lockOwner); - throw new IllegalUnlockException(lockOwner, absPath); - } - catch (RepositoryException e) - { - // This also catch UnsupportedRepositoryOperationException - we assume that implementation supports it (jackrabbit does) - throw new org.apache.portals.graffito.jcr.exception.RepositoryException( - e.getMessage(), e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#isLocked(java.lang.String) - */ - public boolean isLocked(final String absPath) - { - try - { - final Node node = getNode(absPath); - return node.isLocked(); - } - catch (RepositoryException e) - { - // node.isLocked() RepositoryException if an error occurs. - throw new org.apache.portals.graffito.jcr.exception.RepositoryException( - "General error with JCR", e); - } - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#getQueryManager() - */ - public QueryManager getQueryManager() - { - - return this.queryManager; - } - - /** - * Throws {@link LockedException} id node is locked so alter nopde cannot be done - * - * @param absPath - * abs path to node - * @throws RepositoryException - * @throws LockedException - * if node is locked - */ - protected void checkIfNodeLocked(final String absPath) throws RepositoryException, LockedException - { - Node node = getNode(absPath); - // Node can hold nock or can be locked with precedencor - if (node.isLocked()) - { - Lock lock = node.getLock(); - String lockOwner = lock.getLockOwner(); - final String path = lock.getNode().getPath(); - throw new LockedException(lockOwner, path); - } - } - - protected void maybeAddLockToken(final String lockToken) - { - if (lockToken != null) - { - // This user (this instance of PM) potentionally placed lock so - // session already has lock token - final String[] lockTokens = getSession().getLockTokens(); - if (ArrayUtils.contains(lockTokens, lockToken)) - { - // Ok = this session can unlock - } - else - { - getSession().addLockToken(lockToken); - } - } - } - - protected Node getNode(final String absPath) throws PathNotFoundException, - RepositoryException - { - - if (!getSession().itemExists(absPath)) - { - throw new org.apache.portals.graffito.jcr.exception.PersistenceException( - "No object stored on path: " + absPath); - } - Item item = getSession().getItem(absPath); - if (!item.isNode()) - { - throw new org.apache.portals.graffito.jcr.exception.PersistenceException( - "No object stored on path: " + absPath - + " on absPath is item (leaf)"); - } - Node node = (Node) item; - return node; - } - - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#logout() - */ - public void logout() - { - try - { - session.save(); - session.logout(); - } - catch (Exception e) - { - throw new PersistenceException("Impossible to logout", e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.PersistenceManager#save() - */ - public void save() - { - try - { - session.save(); - } - catch (Exception e) - { - throw new PersistenceException("Impossible to save", e); - } - } - - /** - * @return The JCR Session - */ - public Session getSession() - { - return this.session; - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/objectconverter/ObjectConverter.java b/src/java/org/apache/portals/graffito/jcr/persistence/objectconverter/ObjectConverter.java deleted file mode 100644 index a91f4b6a..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/objectconverter/ObjectConverter.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence.objectconverter; - -import javax.jcr.Node; -import javax.jcr.Session; - -import org.apache.portals.graffito.jcr.exception.PersistenceException; - - -/** - * Convert any kind of beans into JCR nodes & properties - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public interface ObjectConverter -{ - /** - * Insert the object - * - * @param session the JCR session - * @param object the object to insert - * @throws PersistenceException when it is not possible to insert the object - * - */ - public void insert(Session session, Object object) throws PersistenceException; - - /** - * Update the object - * - * @param session the JCR session - * @param object the object to update - * @throws PersistenceException when it is not possible to update the object - */ - public void update(Session session, Object object) throws PersistenceException; - - /** - * Retrieve an object from the JCR repo - * - * @param session The JCR session - * @param clazz The class assigned to the object to retrieve - * @param path the JCR path - * @return The object found or null - * - * @throws PersistenceException when it is not possible to retrieve the object - */ - public Object getObject(Session session, Class clazz, String path) throws PersistenceException; - - - /** - * Insert the object - * - * @param session the JCR session - * @param parentNode The parent node used to store the new JCR element (object) - * @param nodeName The node name used to store the object - * @param object the object to insert - * @throws PersistenceException when it is not possible to insert the object - */ - public void insert(Session session, Node parentNode, String nodeName, Object object) throws PersistenceException; - - /** - * Update the object - * - * @param session the JCR session - * @param parentNode The parent node used to store the new JCR element (object) - * @param nodeName The node name used to store the object - * @param object the object to update - * @throws PersistenceException when it is not possible to update the object - */ - public void update(Session session, Node parentNode, String nodeName, Object object) throws PersistenceException; - - - /** - * Get the object JCR path - * - * @param session the JCR session - * @param object the object for which the path has to be retrieve - * @return the object JCR path - * @throws PersistenceException when it is not possible to retrieve the object path - */ - public String getPath(Session session , Object object) throws PersistenceException; - -} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/objectconverter/impl/ObjectConverterImpl.java b/src/java/org/apache/portals/graffito/jcr/persistence/objectconverter/impl/ObjectConverterImpl.java deleted file mode 100644 index 2980363d..00000000 --- a/src/java/org/apache/portals/graffito/jcr/persistence/objectconverter/impl/ObjectConverterImpl.java +++ /dev/null @@ -1,504 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.persistence.objectconverter.impl; - -import java.lang.reflect.InvocationTargetException; -import java.util.Iterator; -import java.util.Map; - -import javax.jcr.Node; -import javax.jcr.PathNotFoundException; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.Value; -import javax.jcr.ValueFormatException; -import javax.jcr.lock.LockException; -import javax.jcr.nodetype.ConstraintViolationException; -import javax.jcr.nodetype.PropertyDefinition; -import javax.jcr.version.VersionException; - -import org.apache.commons.beanutils.ConstructorUtils; -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.portals.graffito.jcr.exception.JcrMappingException; -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.BeanDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.FieldDescriptor; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.CollectionConverter; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollectionUtil; -import org.apache.portals.graffito.jcr.persistence.collectionconverter.impl.DefaultCollectionConverterImpl; -import org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter; -import org.apache.portals.graffito.jcr.repository.RepositoryUtil; - -/** - * Default implementation for {@link ObjectConverterImpl} - * - * @author Lombart Christophe - * - */ -public class ObjectConverterImpl implements ObjectConverter -{ - private Mapper mapper; - - private Map atomicTypeConverters; - - /** - * Constructor - * - * @param mapper The mapper to used - * @param atomicTypeConverters The atomic type converters to used - * - */ - public ObjectConverterImpl(Mapper mapper, Map atomicTypeConverters) - { - this.mapper = mapper; - this.atomicTypeConverters = atomicTypeConverters; - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter#insert(javax.jcr.Session, java.lang.Object) - */ - public void insert(Session session, Object object) - { - String path = this.getPath(session, object); - try - { - String parentPath = RepositoryUtil.getParentPath(path); - String nodeName = RepositoryUtil.getNodeName(path); - Node parentNode = (Node) session.getItem(parentPath); - this.insert(session, parentNode, nodeName, object); - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to insert the object at " + path, e); - } - - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter#insert(javax.jcr.Session, javax.jcr.Node, java.lang.String, java.lang.Object) - */ - public void insert(Session session, Node parentNode, String nodeName, Object object) - { - try - { - ClassDescriptor classDescriptor = mapper.getClassDescriptor(object.getClass()); - if (classDescriptor == null) - { - throw new PersistenceException("Class of type: " + object.getClass().getName() + " is not JCR persistable. Maybe element 'class-descriptor' for this type in mapping file is missing"); - } - - String jcrNodeType = classDescriptor.getJcrNodeType(); - if (jcrNodeType == null || jcrNodeType.equals("")) - { - throw new PersistenceException("Undefined node type for " + parentNode); - } - - Node objectNode = null; - objectNode = parentNode.addNode(nodeName, jcrNodeType); - - storeSimpleFields(object, classDescriptor, objectNode); - insertBeanFields(session, object, classDescriptor, objectNode); - insertCollectionFields(session, object, classDescriptor, objectNode); - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to insert the object at " + parentNode, e); - } - - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter#update(javax.jcr.Session, java.lang.Object) - */ - public void update(Session session, Object object) - { - String path = this.getPath(session, object); - try - { - String parentPath = RepositoryUtil.getParentPath(path); - String nodeName = RepositoryUtil.getNodeName(path); - Node parentNode = (Node) session.getItem(parentPath); - this.update(session, parentNode, nodeName, object); - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to update the object at " + path, e); - } - } - - /** - * - * @see org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter#update(javax.jcr.Session, javax.jcr.Node, java.lang.String, java.lang.Object) - */ - public void update(Session session, Node parentNode, String nodeName, Object object) - { - try - { - ClassDescriptor classDescriptor = mapper.getClassDescriptor(object.getClass()); - if (classDescriptor == null) - { - throw new PersistenceException("Class of type: " + object.getClass().getName() + " is not JCR persistable. Maybe element 'class-descriptor' for this type in mapping file is missing"); - } - - String jcrNodeType = classDescriptor.getJcrNodeType(); - if (jcrNodeType == null || jcrNodeType.equals("")) - { - throw new PersistenceException("Undefined node type for " + parentNode); - } - - Node objectNode = null; - objectNode = parentNode.getNode(nodeName); - - storeSimpleFields(object, classDescriptor, objectNode); - updateBeanFields(session, object, classDescriptor, objectNode); - updateCollectionFields(session, object, classDescriptor, objectNode); - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to update the node : " + parentNode, e); - } - - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.objectconverter.ObjectConverter#getObject(javax.jcr.Session, java.lang.Class, java.lang.String) - */ - public Object getObject(Session session, Class clazz, String path) - { - try - { - - if (!session.itemExists(path)) - { - return null; - } - - ClassDescriptor classDescriptor = mapper.getClassDescriptor(clazz); - if (classDescriptor == null) - { - throw new PersistenceException("Class of type: " + clazz.getName() + " is not JCR persistable. Maybe element 'class-descriptor' for this type in mapping file is missing"); - } - - Node node = (Node) session.getItem(path); - Object object = clazz.newInstance(); - - retrieveSimpleFields(classDescriptor, node, object); - retrieveBeanFields(session, path, classDescriptor, object); - retrieveCollectionFields(session, classDescriptor, node, object); - - return object; - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to get the object at " + path, e); - } - } - - - public String getPath(Session session, Object object) - { - try - { - ClassDescriptor classDescriptor = mapper.getClassDescriptor(object.getClass()); - if (classDescriptor == null) - { - throw new PersistenceException("Class of type: " + object.getClass().getName() + " is not JCR persistable. Maybe element 'class-descriptor' for this type in mapping file is missing"); - } - - final FieldDescriptor pathFieldDescriptor = classDescriptor.getPathFieldDescriptor(); - if (pathFieldDescriptor == null) - { - throw new PersistenceException("Class of type: " + object.getClass().getName() + " has no path mapping. Maybe attribute path=\"true\" for a field element of this class in jcrmapping.xml is missing?"); - } - String pathField = pathFieldDescriptor.getFieldName(); - return (String) PropertyUtils.getNestedProperty(object, pathField); - - - } - catch (Exception e) - { - throw new PersistenceException("Impossible to get the path", e); - } - - } - - /** - * Retrieve simple fields (atomic fields) - */ - private void retrieveSimpleFields(ClassDescriptor classDescriptor, Node node, Object object) throws PathNotFoundException, RepositoryException, ValueFormatException, IllegalAccessException, - InvocationTargetException, NoSuchMethodException - { - Iterator fieldDescriptorIterator = classDescriptor.getFieldDescriptors().iterator(); - - while (fieldDescriptorIterator.hasNext()) - { - FieldDescriptor fieldDescriptor = (FieldDescriptor) fieldDescriptorIterator.next(); - - String fieldName = fieldDescriptor.getFieldName(); - String propertyName = fieldDescriptor.getJcrName(); - - if (fieldDescriptor.isPath()) - { - PropertyUtils.setNestedProperty(object, fieldName, node.getPath()); - } - else - { - Class fieldTypeClass = fieldDescriptor.getFieldTypeClass() != null - ? fieldDescriptor.getFieldTypeClass() - : PropertyUtils.getPropertyType(object, fieldName); - - AtomicTypeConverter converter = (AtomicTypeConverter) atomicTypeConverters - .get(fieldTypeClass); - if (node.hasProperty(propertyName)) - { - Object fieldValue = converter.getObject(node.getProperty(propertyName).getValue()); - PropertyUtils.setNestedProperty(object, fieldName, fieldValue); - } - } - } - } - - /** - * Retrieve bean fields - */ - private void retrieveBeanFields(Session session, String path, ClassDescriptor classDescriptor, Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException - { - Iterator beanDescriptorIterator = classDescriptor.getBeanDescriptors().iterator(); - while (beanDescriptorIterator.hasNext()) - { - BeanDescriptor beanDescriptor = (BeanDescriptor) beanDescriptorIterator.next(); - String beanName = beanDescriptor.getFieldName(); - Class beanClass = PropertyUtils.getPropertyDescriptor(object, beanName).getPropertyType(); - Object bean = this.getObject(session, beanClass, path + "/" + beanDescriptor.getJcrName()); - PropertyUtils.setNestedProperty(object, beanName, bean); - } - } - - /** - * Retrieve Collection fields - */ - private void retrieveCollectionFields(Session session, ClassDescriptor classDescriptor, Node node, Object object) throws PathNotFoundException, RepositoryException, JcrMappingException, - ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException - { - Iterator collectionDescriptorIterator = classDescriptor.getCollectionDescriptors().iterator(); - while (collectionDescriptorIterator.hasNext()) - { - CollectionDescriptor collectionDescriptor = (CollectionDescriptor) collectionDescriptorIterator.next(); - CollectionConverter collectionConverter = this.getCollectionConverter(collectionDescriptor); - Class collectionFieldClass = PropertyUtils.getPropertyDescriptor(object, collectionDescriptor.getFieldName()).getPropertyType(); - ManageableCollection collection = collectionConverter.getCollection(session, node, collectionDescriptor, collectionFieldClass); - PropertyUtils.setNestedProperty(object, collectionDescriptor.getFieldName(), collection); - } - } - - /** - * Insert Bean fields - */ - private void insertBeanFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) - { - try - { - Iterator beanDescriptorIterator = classDescriptor.getBeanDescriptors().iterator(); - while (beanDescriptorIterator.hasNext()) - { - BeanDescriptor beanDescriptor = (BeanDescriptor) beanDescriptorIterator.next(); - String jcrName = beanDescriptor.getJcrName(); - Object bean = PropertyUtils.getNestedProperty(object, beanDescriptor.getFieldName()); - if (bean != null) - { - this.insert(session, objectNode, jcrName, bean); - } - - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to insert the bean fields", e); - } - - } - - /** - * Update Bean fields - */ - private void updateBeanFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) - { - try - { - Iterator beanDescriptorIterator = classDescriptor.getBeanDescriptors().iterator(); - while (beanDescriptorIterator.hasNext()) - { - BeanDescriptor beanDescriptor = (BeanDescriptor) beanDescriptorIterator.next(); - String jcrName = beanDescriptor.getJcrName(); - Object bean = PropertyUtils.getNestedProperty(object, beanDescriptor.getFieldName()); - - // if the bean is null, remove existing node - if ((bean == null)) - { - if (objectNode.hasNode(jcrName)) - { - objectNode.getNode(jcrName).remove(); - } - } - else - { - this.update(session, objectNode, jcrName, bean); - } - - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to update the bean fields", e); - } - - } - - private void insertCollectionFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) - { - try - { - Iterator collectionDescriptorIterator = classDescriptor.getCollectionDescriptors().iterator(); - while (collectionDescriptorIterator.hasNext()) - { - CollectionDescriptor collectionDescriptor = (CollectionDescriptor) collectionDescriptorIterator.next(); - CollectionConverter collectionConverter = this.getCollectionConverter(collectionDescriptor); - Object collection = PropertyUtils.getNestedProperty(object, collectionDescriptor.getFieldName()); - ManageableCollection manageableCollection = ManageableCollectionUtil.getManageableCollection(collection); - collectionConverter.insertCollection(session, objectNode, collectionDescriptor, manageableCollection); - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to insert the collection fields", e); - } - - } - - private void updateCollectionFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) - { - try - { - Iterator collectionDescriptorIterator = classDescriptor.getCollectionDescriptors().iterator(); - while (collectionDescriptorIterator.hasNext()) - { - CollectionDescriptor collectionDescriptor = (CollectionDescriptor) collectionDescriptorIterator.next(); - CollectionConverter collectionConverter = this.getCollectionConverter(collectionDescriptor); - Object collection = PropertyUtils.getNestedProperty(object, collectionDescriptor.getFieldName()); - ManageableCollection manageableCollection = ManageableCollectionUtil.getManageableCollection(collection); - collectionConverter.updateCollection(session, objectNode, collectionDescriptor, manageableCollection); - } - } - catch (Exception e) - { - throw new PersistenceException("Impossible to store the bean fields", e); - } - - } - - private void storeSimpleFields(Object object, ClassDescriptor classDescriptor, Node objectNode) - throws PathNotFoundException, ValueFormatException, VersionException, LockException, ConstraintViolationException, - RepositoryException, IllegalAccessException, InvocationTargetException, NoSuchMethodException - { - - - Iterator fieldDescriptorIterator = classDescriptor.getFieldDescriptors().iterator(); - while (fieldDescriptorIterator.hasNext()) - { - - FieldDescriptor fieldDescriptor = (FieldDescriptor) fieldDescriptorIterator.next(); - - //Of course, Path field is not updated as property - if (fieldDescriptor.isPath()) - { - continue; - } - - String fieldName = fieldDescriptor.getFieldName(); - String jcrName = fieldDescriptor.getJcrName(); - - // Check the node properties - boolean autoCreated = false; - - if (objectNode.hasProperty(jcrName)) - { - autoCreated = objectNode.getProperty(jcrName).getDefinition().isAutoCreated(); - } - - // All auto created JCR properties are ignored - if (!autoCreated) - { - - Object fieldValue = PropertyUtils.getNestedProperty(object, fieldName); - Class fieldTypeClass = fieldDescriptor.getFieldTypeClass() != null - ? fieldDescriptor.getFieldTypeClass() - : PropertyUtils.getPropertyType(object, fieldName); - AtomicTypeConverter converter = (AtomicTypeConverter) atomicTypeConverters.get(fieldTypeClass); - Value value = converter.getValue(fieldValue); - // Check if mandatory property are not null - this.checkMandatoryProperty(objectNode, fieldDescriptor, value); - - objectNode.setProperty(jcrName, value); - } - - } - - } - - private CollectionConverter getCollectionConverter(CollectionDescriptor collectionDescriptor) - throws ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalAccessException - { - - String className = collectionDescriptor.getCollectionConverterClassName(); - if (className == null) - { - return new DefaultCollectionConverterImpl(this.atomicTypeConverters, this, this.mapper); - } - else - { - Class converterClass = Class.forName(className); - Object[] param = - { this.atomicTypeConverters, this, this.mapper }; - return (CollectionConverter) ConstructorUtils.invokeConstructor(converterClass, param); - } - - } - - private void checkMandatoryProperty(Node objectNode, FieldDescriptor fieldDescriptor, Value value) throws RepositoryException - { - PropertyDefinition[] propertyDefinitions = objectNode.getPrimaryNodeType().getDeclaredPropertyDefinitions(); - for (int i = 0; i < propertyDefinitions.length; i++) - { - PropertyDefinition definition = propertyDefinitions[i]; - if (definition.getName().equals(fieldDescriptor.getJcrName()) && definition.isMandatory() && definition.isAutoCreated() == false && value == null) - { - throw new PersistenceException("Class of type:" + fieldDescriptor.getClassDescriptor().getClassName() + " has property: " + fieldDescriptor.getFieldName() - + " declared as JCR property: " + fieldDescriptor.getJcrName() + " This property is mandatory but property in bean has value null"); - } - } - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/query/Filter.java b/src/java/org/apache/portals/graffito/jcr/query/Filter.java deleted file mode 100644 index 7bcb3260..00000000 --- a/src/java/org/apache/portals/graffito/jcr/query/Filter.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.query; - -import org.apache.portals.graffito.jcr.exception.IncorrectAtomicTypeException; - - -/** - * - * Graffito JCR Filter interface. - * - * @author Christophe Lombart - * - */ -public interface Filter -{ - - - /** - * Set the filter scope. The scope is an Node path specifying where to search in the content tree. - * For example, - * /mynode/mysecondnode/', the search engine will search on child objects in the /mynode/mysecondnode - * /mynode/mysecondnode//', the search engine will search on desncendant objects in the /mynode/mysecondnode (the complete subnode tree) - * - * @param scope The filter scope - * - */ - public void setScope(String scope); - - - /** - * Get the filter scope. - * - * @return The filter scope - */ - public String getScope(); - - - /** - * Search content based on a fullTextSearch. - * Depending on the full text search engine, you can also filter on properties. - * - * @param scope either a a jcr node or propserty. If a node is used, all properties of this node are searche (following the internal index - * @param fullTextSearch The full text search string - */ - public void addContains(String scope, String fullTextSearch) throws IncorrectAtomicTypeException; - - public void addBetween(String arg0, Object arg1, Object arg2) throws IncorrectAtomicTypeException; - - public void addEqualTo(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addGreaterOrEqualThan(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addGreaterThan(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addLessOrEqualThan(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addLessThan(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addLike(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addNotEqualTo(String arg0, Object arg1) throws IncorrectAtomicTypeException; - - public void addNotNull(String arg0) throws IncorrectAtomicTypeException; - - public void addIsNull(String arg0) throws IncorrectAtomicTypeException; - - public void addOrFilter(Filter arg0) throws IncorrectAtomicTypeException; - - public void addJCRExpression(String jcrExpression) throws IncorrectAtomicTypeException; - - public Class getFilterClass(); - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/query/impl/FilterImpl.java b/src/java/org/apache/portals/graffito/jcr/query/impl/FilterImpl.java deleted file mode 100644 index db0737ff..00000000 --- a/src/java/org/apache/portals/graffito/jcr/query/impl/FilterImpl.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.query.impl; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter; -import org.apache.portals.graffito.jcr.query.Filter; - -/** - * {@link org.apache.portals.graffito.jcr.query.Filter} - * - * @author Christophe Lombart - * - */ -public class FilterImpl implements Filter -{ - - private Class claszz; - private String scope = ""; - private ArrayList jcrExpressions = new ArrayList(); - - - private ClassDescriptor classDescriptor; - private Map atomicTypeConverters; - - private String orJcrExpression; - - private final static Log log = LogFactory.getLog(FilterImpl.class); - - /** - * Construtor - * - * @param classDescriptor - * @param atomicTypeConverters - * @param clazz - */ - public FilterImpl(ClassDescriptor classDescriptor, Map atomicTypeConverters, Class clazz) - { - this.claszz = clazz; - this.atomicTypeConverters = atomicTypeConverters; - this.classDescriptor = classDescriptor; - } - - - /** - * - * @see org.apache.portals.graffito.jcr.query.Filter#getFilterClass() - */ - public Class getFilterClass() - { - return claszz; - } - - - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#setScope(java.lang.String) - */ - public void setScope(String scope) - { - this.scope = scope; - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#getScope() - */ - public String getScope() - { - - return this.scope; - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addContains(java.lang.String) - */ - public void addContains(String scope, String fullTextSearch) - { - String jcrExpression = null; - if (scope.equals(".")) - { - jcrExpression = "jcr:contains(., '" + fullTextSearch + "')"; - } - else - { - jcrExpression = "jcr:contains(@" + this.getJcrFieldName(scope) + ", '" + fullTextSearch + "')"; - } - - jcrExpressions.add(jcrExpression); - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addBetween(java.lang.String, java.lang.Object, java.lang.Object) - */ - public void addBetween(String fieldAttributeName, Object value1, Object value2) - { - String jcrExpression = "( @" + this.getJcrFieldName(fieldAttributeName) + " >= " + this.getStringValue(value1) + - " and @" + this.getJcrFieldName(fieldAttributeName) + " <= " + this.getStringValue(value2) + ")"; - jcrExpressions.add(jcrExpression) ; - - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addEqualTo(java.lang.String, java.lang.Object) - */ - public void addEqualTo(String fieldAttributeName, Object value) - { - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " = " + this.getStringValue(value); - jcrExpressions.add(jcrExpression); - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addGreaterOrEqualThan(java.lang.String, java.lang.Object) - */ - public void addGreaterOrEqualThan(String fieldAttributeName, Object value) - { - - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " >= " + this.getStringValue(value); - jcrExpressions.add(jcrExpression); - - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addGreaterThan(java.lang.String, java.lang.Object) - */ - public void addGreaterThan(String fieldAttributeName, Object value) - { - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " > " + this.getStringValue(value); - jcrExpressions.add(jcrExpression); - - } - - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addLessOrEqualThan(java.lang.String, java.lang.Object) - */ - public void addLessOrEqualThan(String fieldAttributeName, Object value) - { - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " <= " + this.getStringValue(value); - jcrExpressions.add(jcrExpression); - - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addLessOrEqualThan(java.lang.String, java.lang.Object) - */ - public void addLessThan(String fieldAttributeName, Object value) - { - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " < " + this.getStringValue(value); - jcrExpressions.add(jcrExpression); - - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addLike(java.lang.Object, java.lang.Object) - */ - public void addLike(String fieldAttributeName, Object value) - { - String jcrExpression = "jcr:like(" + "@" + this.getJcrFieldName(fieldAttributeName) + ", '" + value + "')"; - jcrExpressions.add(jcrExpression); - } - - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addNotEqualTo(java.lang.String, java.lang.Object) - */ - public void addNotEqualTo(String fieldAttributeName, Object value) - { - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " != " + this.getStringValue(value); - jcrExpressions.add(jcrExpression); - } - - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addNotNull(java.lang.String) - */ - public void addNotNull(String fieldAttributeName) - { - String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName); - jcrExpressions.add(jcrExpression); - - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addIsNull(java.lang.String) - */ - public void addIsNull(String fieldAttributeName) - { - String jcrExpression = "not(@" + this.getJcrFieldName(fieldAttributeName)+")"; - jcrExpressions.add(jcrExpression); - - } - - /** - * @see org.apache.portals.graffito.jcr.query.Filter#addOrFilter(org.apache.portals.graffito.jcr.query.Filter) - */ - public void addOrFilter(Filter filter) - { - - orJcrExpression = ((FilterImpl)filter).getJcrExpression(); - - } - - public void addJCRExpression(String jcrExpression) - { - jcrExpressions.add(jcrExpression); - } - - - private String getJcrFieldName(String fieldAttribute) - { - String jcrFieldName = classDescriptor.getJcrName(fieldAttribute); - if (jcrFieldName == null) - { - log.error("Impossible to find the jcrFieldName for the attribute :" + fieldAttribute); - } - return jcrFieldName; - - } - - private String getStringValue (Object value) - { - AtomicTypeConverter atomicTypeConverter = (AtomicTypeConverter) atomicTypeConverters.get(value.getClass()); - return atomicTypeConverter.getStringValue(value); - } - - public String getJcrExpression() - { - if (orJcrExpression == null || orJcrExpression.equals("")) - { - return buildJcrExpression(); - } - else - { - return "(" + buildJcrExpression() + ") or (" + this.orJcrExpression + ")"; - } - - } - - private String buildJcrExpression() - { - int count = 1; - String jcrExp = ""; - - - Iterator criteriaIterator = jcrExpressions.iterator(); - while (criteriaIterator.hasNext()) - { - if (count > 1) - { - jcrExp += " and "; - } - jcrExp += (String) criteriaIterator.next(); - count++; - - } - - - return jcrExp; - - } - - - -} diff --git a/src/java/org/apache/portals/graffito/jcr/query/impl/QueryImpl.java b/src/java/org/apache/portals/graffito/jcr/query/impl/QueryImpl.java deleted file mode 100644 index b6a017d5..00000000 --- a/src/java/org/apache/portals/graffito/jcr/query/impl/QueryImpl.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.query.impl; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; - -/** - * Default Query implementation - * - * @author Christophe Lombart - * - */ -public class QueryImpl implements Query -{ - - private Filter filter; - - ClassDescriptor classDescriptor; - - private ArrayList orderByExpressions = new ArrayList(); - - /** - * Constructor - * - * @param filter - * @param mapper - */ - public QueryImpl(Filter filter, Mapper mapper) - { - this.filter = filter; - classDescriptor = mapper.getClassDescriptor(filter.getFilterClass()); - } - - /** - * @see org.apache.portals.graffito.jcr.query.Query#setFilter(org.apache.portals.graffito.jcr.query.Filter) - */ - public void setFilter(Filter filter) - { - this.filter = filter; - } - - /** - * @see org.apache.portals.graffito.jcr.query.Query#getFilter() - */ - public Filter getFilter() - { - return this.filter; - } - - public void addOrderByDescending(String fieldNameAttribute) - { - orderByExpressions.add("@" + this.getJcrFieldName(fieldNameAttribute) + " descending"); - } - - /** - * - * @see org.apache.portals.graffito.jcr.query.Query#addOrderByAscending(java.lang.String) - */ - public void addOrderByAscending(String fieldNameAttribute) - { - orderByExpressions.add("@" + this.getJcrFieldName(fieldNameAttribute) + " ascending"); - } - - public String getOrderByExpression() - { - - if (orderByExpressions.size() == 0) - { - return ""; - } - - String orderByExpression = "order by "; - Iterator iterator = orderByExpressions.iterator(); - int count=1; - while (iterator.hasNext()) - { - if (count > 1) - { - orderByExpression += " , "; - } - orderByExpression+= (String) iterator.next(); - count++; - } - - return orderByExpression; - } - - - private String getJcrFieldName(String fieldAttribute) - { - - return classDescriptor.getJcrName(fieldAttribute); - - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/query/impl/QueryManagerImpl.java b/src/java/org/apache/portals/graffito/jcr/query/impl/QueryManagerImpl.java deleted file mode 100644 index 16daab97..00000000 --- a/src/java/org/apache/portals/graffito/jcr/query/impl/QueryManagerImpl.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.query.impl; - -import java.util.Map; - -import org.apache.portals.graffito.jcr.mapper.Mapper; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; - -public class QueryManagerImpl implements QueryManager -{ - - private Mapper mapper; - private Map atomicTypeConverters; - public QueryManagerImpl(Mapper mapper, Map atomicTypeConverters) - { - this.mapper = mapper; - this.atomicTypeConverters = atomicTypeConverters; - } - - public Filter createFilter(Class classQuery) - { - - return new FilterImpl(mapper.getClassDescriptor(classQuery), atomicTypeConverters, classQuery); - } - - public Query createQuery(Filter filter) - { - - return new QueryImpl(filter, mapper); - } - - public String buildJCRExpression(Query query) - { - - Filter filter = query.getFilter(); - - String jcrExp = ""; - - // Add scope - if ((filter.getScope() != null && ( ! filter.getScope().equals("")))) - { - jcrExp += "/jcr:root" + filter.getScope() + "element(*, "; - } - else - { - jcrExp += "//element(*, "; - } - - // Add node type - jcrExp += this.getNodeType(filter) + ") "; - - // Add filter criteria - String filterExp = ((FilterImpl)filter).getJcrExpression(); - if ((filterExp != null) && ( ! filterExp.equals(""))) - { - jcrExp += "[" + filterExp + "]"; - } - - // Add order by - jcrExp += ((QueryImpl)query).getOrderByExpression(); - - return jcrExp; - - } - - private String getNodeType(Filter filter) - { - ClassDescriptor classDescriptor = mapper.getClassDescriptor(filter.getFilterClass()); - return classDescriptor.getJcrNodeType(); - - } - -} diff --git a/src/java/org/apache/portals/graffito/jcr/repository/RepositoryUtil.java b/src/java/org/apache/portals/graffito/jcr/repository/RepositoryUtil.java deleted file mode 100644 index 895c60a6..00000000 --- a/src/java/org/apache/portals/graffito/jcr/repository/RepositoryUtil.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.repository; - -import java.util.Hashtable; - -import javax.jcr.Repository; -import javax.jcr.Session; -import javax.jcr.SimpleCredentials; -import javax.naming.Context; -import javax.naming.InitialContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.jackrabbit.core.jndi.RegistryHelper; -import org.apache.jackrabbit.util.ISO9075; -import org.apache.jackrabbit.util.Text; -import org.apache.portals.graffito.jcr.exception.PersistenceException; -import org.apache.portals.graffito.jcr.exception.RepositoryException; - -/** -* Utility class for managing JCR repositories. -* -* @author Lombart Christophe -* @version $Id: Exp $ -*/ -public class RepositoryUtil -{ - - /** Graffito namespace prefix constant. - */ - private static final String GRAFFITO_NAMESPACE_PREFIX = "graffito"; - - /** Graffito namespace constant. - */ - private static final String GRAFFITO_NAMESPACE = "http://incubator.apache.org/graffito"; - /** Item path separator */ - public static final String PATH_SEPARATOR = "/"; - - private final static Log log = LogFactory.getLog(RepositoryUtil.class); - /** - * Register a new repository - * - * @param repositoryName The repository unique name - * @param configFile The JCR config file - * @param homeDir The directory containing the complete repository settings (workspace, node types, ...) - * - * @throws RepositoryException when it is not possible to register the repository - */ - public static void registerRepository(String repositoryName, String configFile, String homeDir) throws RepositoryException - { - try - { - Hashtable env = new Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); - env.put(Context.PROVIDER_URL, "localhost"); - InitialContext ctx = new InitialContext(env); - - RegistryHelper.registerRepository(ctx, repositoryName, configFile, homeDir, true); - - } - catch (Exception e) - { - throw new RepositoryException("Impossible to register the respository : " + - repositoryName + " - config file : " + configFile, e); - } - - } - - - /** - * Unregister a repository - * - * @param repositoryName The repository unique name - * - * @throws RepositoryException when it is not possible to unregister the repository - */ - public static void unRegisterRepository(String repositoryName) throws RepositoryException - { - try - { - - - Hashtable env = new Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); - env.put(Context.PROVIDER_URL, "localhost"); - InitialContext ctx = new InitialContext(env); - - RegistryHelper.unregisterRepository(ctx, repositoryName); - - } - catch (Exception e) - { - throw new RepositoryException("Impossible to unregister the respository : " + - repositoryName , e); - } - - } - - /** - * Get a repository - * - * @param repositoryName The repository name - * @return a JCR repository reference - * - * @throws RepositoryException when it is not possible to get the repository. - * Before calling this method, the repository has to be registered (@see RepositoryUtil#registerRepository(String, String, String) - */ - public static Repository getRepository(String repositoryName) throws RepositoryException - { - try - { - Hashtable env = new Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); - env.put(Context.PROVIDER_URL, "localhost"); - InitialContext ctx = new InitialContext(env); - - Repository repository = (Repository) ctx.lookup(repositoryName); - return repository; - } - catch (Exception e) - { - throw new RepositoryException("Impossible to get the repository : " + repositoryName, e); - } - } - - /** - * Connect to a JCR repository - * - * @param repository The JCR repository - * @param user The user name - * @param password The password - * @return a valid JCR session - * - * @throws RepositoryException when it is not possible to connect to the JCR repository - */ - public static Session login(Repository repository, String user, String password) throws RepositoryException - { - try - { - Session session = repository.login(new SimpleCredentials(user, password.toCharArray()), null); - setupSession(session); - - return session; - - } - catch (Exception e) - { - throw new RepositoryException("Impossible to login ", e); - } - } - - /** - * Check if a path is valid - * - * @param path The path to validate - * @return true if the path is valid, else false - */ - public static boolean isValidPath(String path) - { - if ((path == null) || - (path.equals(PATH_SEPARATOR)) || - (path.endsWith(PATH_SEPARATOR)) || - (! path.startsWith(PATH_SEPARATOR)) || - (path.equals(""))) - { - return false; - } - return true; - } - - /** - * Get the parent path - * @param path The path from wich the parent path has to be returned - * @return The parent path - * - * @throws PersistenceException when the path is invalid - */ - public static String getParentPath(String path) throws PersistenceException - { - String parentPath = ""; - - if (!isValidPath(path)) - { - throw new PersistenceException("Invalid path : " + path); - } - - String[] pathElements = path.split(PATH_SEPARATOR); - - // Firts path element should be = empty string because a uri always start with '/' - // So, if len=2, means it is a root folder like '/foo'. - // In this case the uri has not parent folder => return "/" - if (pathElements.length == 2) - { - return PATH_SEPARATOR; - } - - for(int i=0; i < pathElements.length -1; i++) - { - if (! pathElements[i].equals("")) - { - parentPath += PATH_SEPARATOR + pathElements[i]; - } - } - return parentPath; - } - - /** - * Get the node name - * @param path The path from which the node name has to be retrieved - * @return The node name - * - * @throws PersistenceException when the path is invalid - */ - public static String getNodeName(String path) throws PersistenceException - { - - String[] pathElements = path.split(PATH_SEPARATOR); - - if (! isValidPath(path)) - { - throw new PersistenceException("Invalid path : " + path); - } - return pathElements[pathElements.length-1]; - } - - /** - * Setup the session. - * Until now, we check only if the Graffito namespace prefix exist in the repository - * - */ - private static void setupSession(Session session) throws RepositoryException - { - try - { - String[] jcrNamespaces = session.getWorkspace().getNamespaceRegistry().getPrefixes(); - boolean createGraffitoNamespace = true; - for (int i = 0; i < jcrNamespaces.length; i++) - { - if (jcrNamespaces[i].equals(GRAFFITO_NAMESPACE_PREFIX)) - { - createGraffitoNamespace = false; - log.debug("Graffito namespace exists."); - } - } - - if (createGraffitoNamespace) - { - session.getWorkspace().getNamespaceRegistry().registerNamespace(GRAFFITO_NAMESPACE_PREFIX, GRAFFITO_NAMESPACE); - log.info("Successfully created graffito namespace."); - } - - if (session.getRootNode() != null) - { - log.info("Jcr repository setup successfull."); - } - - - } - catch (Exception e) - { - log.error("Error while setting up the jcr repository.", e); - throw new RepositoryException(e.getMessage()); - } - } - - /** - * Encode a path - * @TODO : drop Jackrabbit dependency - * - * @param path the path to encode - * @return the encoded path - * - */ - public static String encodePath(String path) - { - String[] pathElements = Text.explode(path, '/'); - for (int i=0;iSimpleAccessManager ... - */ -public class SimpleAccessManager implements AccessManager -{ - - private static Logger log = Logger.getLogger(SimpleAccessManager.class); - - /** - * Subject whose access rights this AccessManager should reflect - */ - protected Subject subject; - - /** - * hierarchy manager used for ACL-based access control model - */ - protected HierarchyManager hierMgr; - - private boolean initialized; - - protected boolean system; - - protected boolean anonymous; - - /** - * Empty constructor - */ - public SimpleAccessManager() - { - initialized = false; - anonymous = false; - system = false; - } - - //--------------------------------------------------------< AccessManager > - /** - * {@inheritDoc} - */ - public void init(AMContext context) throws AccessDeniedException, Exception - { - if (initialized) - { - throw new IllegalStateException("already initialized"); - } - - subject = context.getSubject(); - hierMgr = context.getHierarchyManager(); - anonymous = !subject.getPrincipals(AnonymousPrincipal.class).isEmpty(); - system = !subject.getPrincipals(SystemPrincipal.class).isEmpty(); - - // @todo check permission to access given workspace based on principals - initialized = true; - } - - /** - * {@inheritDoc} - */ - public synchronized void close() throws Exception - { - if (!initialized) - { - throw new IllegalStateException("not initialized"); - } - - initialized = false; - } - - /** - * {@inheritDoc} - */ - public void checkPermission(ItemId id, int permissions) throws AccessDeniedException, ItemNotFoundException, RepositoryException - { - if (!initialized) - { - throw new IllegalStateException("not initialized"); - } - - if (system) - { - // system has always all permissions - return; - } - else if (anonymous) - { - // anonymous is always denied WRITE & REMOVE premissions - if ((permissions & WRITE) == WRITE || (permissions & REMOVE) == REMOVE) - { - throw new AccessDeniedException(); - } - } - // @todo check permission based on principals - } - - /** - * {@inheritDoc} - */ - public boolean isGranted(ItemId id, int permissions) throws ItemNotFoundException, RepositoryException - { - if (!initialized) - { - throw new IllegalStateException("not initialized"); - } - - if (system) - { - // system has always all permissions - return true; - } - else if (anonymous) - { - // anonymous is always denied WRITE & REMOVE premissions - if ((permissions & WRITE) == WRITE || (permissions & REMOVE) == REMOVE) - { - return false; - } - } - - // @todo check permission based on principals - return true; - - - } - - /** - * {@inheritDoc} - */ - public boolean canAccess(String workspaceName) throws NoSuchWorkspaceException, RepositoryException - { - // @todo check permission to access given workspace based on principals - return true; - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/security/SimpleLoginModule.java b/src/java/org/apache/portals/graffito/jcr/security/SimpleLoginModule.java deleted file mode 100644 index 0cfbc68c..00000000 --- a/src/java/org/apache/portals/graffito/jcr/security/SimpleLoginModule.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.security; - -import org.apache.jackrabbit.core.security.AnonymousPrincipal; -import org.apache.jackrabbit.core.security.CredentialsCallback; -import org.apache.jackrabbit.core.security.SecurityConstants; -import org.apache.jackrabbit.core.security.UserPrincipal; -import org.apache.log4j.Logger; - -import javax.jcr.Credentials; -import javax.jcr.SimpleCredentials; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.FailedLoginException; -import javax.security.auth.login.LoginException; -import javax.security.auth.spi.LoginModule; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * A SimpleLoginModule ... - */ -public class SimpleLoginModule implements LoginModule -{ - - private static Logger log = Logger.getLogger(SimpleLoginModule.class); - - /** - * Name of the anonymous user id option in the LoginModule configuration - */ - private static final String OPT_ANONYMOUS = "anonymousId"; - - /** - * The default user id for anonymous login - */ - private static final String DEFAULT_ANONYMOUS_ID = "anonymous"; - - // initial state - private Subject subject; - - private CallbackHandler callbackHandler; - - private Map sharedState; - - private Map options; - - // configurable options - //private boolean someOpt = false; - - // local authentication state: - // the principals, i.e. the authenticated identities - private final Set principals = new HashSet(); - - /** - * Id of an anonymous user login - */ - private String anonymousUserId = DEFAULT_ANONYMOUS_ID; - - /** - * Constructor - */ - public SimpleLoginModule() - { - } - - //----------------------------------------------------------< LoginModule > - /** - * {@inheritDoc} - */ - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) - { - this.subject = subject; - this.callbackHandler = callbackHandler; - this.sharedState = sharedState; - this.options = options; - - // initialize any configured options - //someOpt = "true".equalsIgnoreCase((String)options.get("someOpt")); - String userId = (String) options.get(OPT_ANONYMOUS); - if (userId != null) - { - anonymousUserId = userId; - } - } - - /** - * {@inheritDoc} - */ - public boolean login() throws LoginException - { - // prompt for a user name and password - if (callbackHandler == null) - { - throw new LoginException("no CallbackHandler available"); - } - - Callback[] callbacks = new Callback[] - { new CredentialsCallback() }; - - boolean authenticated = false; - principals.clear(); - try - { - callbackHandler.handle(callbacks); - // credentials - CredentialsCallback ccb = (CredentialsCallback) callbacks[0]; - Credentials creds = ccb.getCredentials(); - if (creds != null) - { - if (creds instanceof SimpleCredentials) - { - SimpleCredentials sc = (SimpleCredentials) creds; - // authenticate - - Object attr = sc.getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE); - if (attr != null && attr instanceof Subject) - { - Subject impersonator = (Subject) attr; - // @todo check privileges to 'impersonate' the user represented by the supplied credentials - } - else - { - // @todo implement simple username/password authentication - } - - if (anonymousUserId.equals(sc.getUserID())) - { - principals.add(new AnonymousPrincipal()); - } - else - { - // else assume the user we authenticated is the UserPrincipal - principals.add(new UserPrincipal(sc.getUserID())); - } - authenticated = true; - } - } - } - catch (java.io.IOException ioe) - { - throw new LoginException(ioe.toString()); - } - catch (UnsupportedCallbackException uce) - { - throw new LoginException(uce.getCallback().toString() + " not available"); - } - - if (authenticated) - { - return !principals.isEmpty(); - } - else - { - // authentication failed: clean out state - principals.clear(); - throw new FailedLoginException(); - } - } - - /** - * {@inheritDoc} - */ - public boolean commit() throws LoginException - { - if (principals.isEmpty()) - { - return false; - } - else - { - // add a principals (authenticated identities) to the Subject - subject.getPrincipals().addAll(principals); - return true; - } - } - - /** - * {@inheritDoc} - */ - public boolean abort() throws LoginException - { - if (principals.isEmpty()) - { - return false; - } - else - { - logout(); - } - return true; - } - - /** - * {@inheritDoc} - */ - public boolean logout() throws LoginException - { - subject.getPrincipals().removeAll(principals); - principals.clear(); - return true; - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/transaction/jackrabbit/UserTransactionImpl.java b/src/java/org/apache/portals/graffito/jcr/transaction/jackrabbit/UserTransactionImpl.java deleted file mode 100644 index 913febf9..00000000 --- a/src/java/org/apache/portals/graffito/jcr/transaction/jackrabbit/UserTransactionImpl.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.transaction.jackrabbit; - -import javax.transaction.xa.XAResource; -import javax.transaction.xa.Xid; -import javax.transaction.xa.XAException; -import javax.transaction.UserTransaction; -import javax.transaction.Status; -import javax.transaction.NotSupportedException; -import javax.transaction.SystemException; -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.RollbackException; -import javax.jcr.Session; - -import org.apache.jackrabbit.core.XASession; - -/** - * Internal {@link javax.transaction.UserTransaction} implementation. - */ -public class UserTransactionImpl implements UserTransaction { - - /** - * Global transaction id counter - */ - private static byte counter = 0; - - /** - * XAResource - */ - private final XAResource xares; - - /** - * Xid - */ - private Xid xid; - - /** - * Status - */ - private int status = Status.STATUS_NO_TRANSACTION; - - /** - * Create a new instance of this class. Takes a session as parameter. - * @param session session. If session is not of type - * {@link XASession}, an IllegalArgumentException - * is thrown - */ - public UserTransactionImpl(Session session) { - if (session instanceof XASession) { - xares = ((XASession) session).getXAResource(); - } else { - throw new IllegalArgumentException("Session not of type XASession"); - } - } - - /** - * @see javax.transaction.UserTransaction#begin - */ - public void begin() throws NotSupportedException, SystemException { - if (status != Status.STATUS_NO_TRANSACTION) { - throw new IllegalStateException("Transaction already active"); - } - - try { - xid = new XidImpl(counter++); - xares.start(xid, XAResource.TMNOFLAGS); - status = Status.STATUS_ACTIVE; - - } catch (XAException e) { - - throw new SystemException("Unable to begin transaction: " + - "XA_ERR=" + e.errorCode); - } - } - - /** - * @see javax.transaction.UserTransaction#commit - */ - public void commit() throws HeuristicMixedException, - HeuristicRollbackException, IllegalStateException, - RollbackException, SecurityException, SystemException { - - if (status != Status.STATUS_ACTIVE) { - throw new IllegalStateException("Transaction not active"); - } - - try { - xares.end(xid, XAResource.TMSUCCESS); - - status = Status.STATUS_PREPARING; - xares.prepare(xid); - status = Status.STATUS_PREPARED; - - status = Status.STATUS_COMMITTING; - xares.commit(xid, false); - status = Status.STATUS_COMMITTED; - - } catch (XAException e) { - - if (e.errorCode >= XAException.XA_RBBASE && - e.errorCode <= XAException.XA_RBEND) { - throw new RollbackException(); - } else { - throw new SystemException("Unable to commit transaction: " + - "XA_ERR=" + e.errorCode); - } - } - } - - /** - * @see javax.transaction.UserTransaction#getStatus - */ - public int getStatus() throws SystemException { - return status; - } - - /** - * @see javax.transaction.UserTransaction#rollback - */ - public void rollback() throws IllegalStateException, SecurityException, - SystemException { - - if (status != Status.STATUS_ACTIVE && - status != Status.STATUS_MARKED_ROLLBACK) { - - throw new IllegalStateException("Transaction not active"); - } - - try { - xares.end(xid, XAResource.TMFAIL); - - status = Status.STATUS_ROLLING_BACK; - xares.rollback(xid); - status = Status.STATUS_ROLLEDBACK; - - } catch (XAException e) { - - throw new SystemException("Unable to rollback transaction: " + - "XA_ERR=" + e.errorCode); - } - } - - /** - * @see javax.transaction.UserTransaction#setRollbackOnly() - */ - public void setRollbackOnly() throws IllegalStateException, SystemException { - if (status != Status.STATUS_ACTIVE) { - throw new IllegalStateException("Transaction not active"); - } - status = Status.STATUS_MARKED_ROLLBACK; - } - - /** - * @see javax.transaction.UserTransaction#setTransactionTimeout - */ - public void setTransactionTimeout(int seconds) throws SystemException {} - - - /** - * Internal {@link Xid} implementation. - */ - class XidImpl implements Xid { - - /** Global transaction id */ - private final byte[] globalTxId; - - /** - * Create a new instance of this class. Takes a global - * transaction number as parameter - * @param globalTxNumber global transaction number - */ - public XidImpl(byte globalTxNumber) { - this.globalTxId = new byte[] { globalTxNumber }; - } - - /** - * @see javax.transaction.xa.Xid#getFormatId() - */ - public int getFormatId() { - return 0; - } - - /** - * @see javax.transaction.xa.Xid#getBranchQualifier() - */ - public byte[] getBranchQualifier() { - return new byte[0]; - } - - /** - * @see javax.transaction.xa.Xid#getGlobalTransactionId() - */ - public byte[] getGlobalTransactionId() { - return globalTxId; - } - } -} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/CustomNodeTypeCreationException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/CustomNodeTypeCreationException.java similarity index 75% rename from src/java/org/apache/portals/graffito/jcr/exception/CustomNodeTypeCreationException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/CustomNodeTypeCreationException.java index 22bae1ff..5a097c75 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/CustomNodeTypeCreationException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/CustomNodeTypeCreationException.java @@ -1,57 +1,58 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** This exception is thrown during repository setup while creating the - * custom graffito node types. - * - * @author Oliver Kiessler - * @version $Id: Exp $ - */ -public class CustomNodeTypeCreationException extends JcrMappingException { - - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = 3991714987182739219L; - - /** - * Constructor with message. - * - * @param message the message associated to the exception - */ - public CustomNodeTypeCreationException(String message) { - super(message); - } - - /** - * Constructor with throwable object. - * - * @param nested the associated throwable object - */ - public CustomNodeTypeCreationException(Throwable nested) { - super(nested); - } - - /** - * Constructor with message and throwable object. - * - * @param message the message associated to the exception - * @param nested the associated throwable object - */ - public CustomNodeTypeCreationException(String message, Throwable nested) { - super(message, nested); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** This exception is thrown during repository setup while creating the + * custom node types. + * + * @author Oliver Kiessler + * @version $Id: Exp $ + */ +public class CustomNodeTypeCreationException extends JcrMappingException { + + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = 3991714987182739219L; + + /** + * Constructor with message. + * + * @param message the message associated to the exception + */ + public CustomNodeTypeCreationException(String message) { + super(message); + } + + /** + * Constructor with throwable object. + * + * @param nested the associated throwable object + */ + public CustomNodeTypeCreationException(Throwable nested) { + super(nested); + } + + /** + * Constructor with message and throwable object. + * + * @param message the message associated to the exception + * @param nested the associated throwable object + */ + public CustomNodeTypeCreationException(String message, Throwable nested) { + super(message, nested); + } +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/IllegalUnlockException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/IllegalUnlockException.java similarity index 72% rename from src/java/org/apache/portals/graffito/jcr/exception/IllegalUnlockException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/IllegalUnlockException.java index 7191fbe6..b92bf66d 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/IllegalUnlockException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/IllegalUnlockException.java @@ -1,56 +1,57 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** - * If user cannot unlock path, for example if he/she have not correct lockTokens - * - * @author Martin Koci - * @author Alexandru Popescu - */ -public class IllegalUnlockException extends LockingException { - - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = 5078216219061716697L; - - private final String lockOwner; - - private final String path; - - /** - * - * @return The JCR Lock Owner - */ - public String getLockOwner() { - return lockOwner; - } - - /** - * - * @return the JCR path - */ - public String getPath() { - return path; - } - - public IllegalUnlockException(String lockOwner, String path) { - super(); - this.lockOwner = lockOwner; - this.path = path; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** + * If user cannot unlock path, for example if he/she have not correct lockTokens + * + * @author Martin Koci + * @author Alexandru Popescu + */ +public class IllegalUnlockException extends LockingException { + + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = 5078216219061716697L; + + private final String lockOwner; + + private final String path; + + /** + * + * @return The JCR Lock Owner + */ + public String getLockOwner() { + return lockOwner; + } + + /** + * + * @return the JCR path + */ + public String getPath() { + return path; + } + + public IllegalUnlockException(String lockOwner, String path) { + super(); + this.lockOwner = lockOwner; + this.path = path; + } + +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/IncorrectAtomicTypeException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/IncorrectAtomicTypeException.java similarity index 71% rename from src/java/org/apache/portals/graffito/jcr/exception/IncorrectAtomicTypeException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/IncorrectAtomicTypeException.java index f09d6579..84f598d3 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/IncorrectAtomicTypeException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/IncorrectAtomicTypeException.java @@ -1,44 +1,44 @@ -/* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.exception; - - -/** - * Occurs when the jcr mapping converters try to assign or read an incorrect atomic field type. - * - * @author Christophe Lombart - * @author Alexandru Popescu - */ -public class IncorrectAtomicTypeException extends JcrMappingException { - - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = 8819724602193665601L; - - public IncorrectAtomicTypeException(String message, Throwable nested) { - super(message, nested); - } - - public IncorrectAtomicTypeException(String message) { - super(message); - } - - public IncorrectAtomicTypeException(Throwable nested) { - super(nested); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.exception; + + +/** + * Occurs when the jcr mapping converters try to assign or read an incorrect atomic field type. + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class IncorrectAtomicTypeException extends JcrMappingException { + + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = 8819724602193665601L; + + public IncorrectAtomicTypeException(String message, Throwable nested) { + super(message, nested); + } + + public IncorrectAtomicTypeException(String message) { + super(message); + } + + public IncorrectAtomicTypeException(Throwable nested) { + super(nested); + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/exception/IncorrectPersistentClassException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/IncorrectPersistentClassException.java new file mode 100644 index 00000000..28e76603 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/IncorrectPersistentClassException.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.exception; + + +/** + * Occurs when the ocm try to manage an object which is not based on a persistent class. + * + * @author Christophe Lombart + */ +public class IncorrectPersistentClassException extends JcrMappingException { + + + public IncorrectPersistentClassException(String message, Throwable nested) { + super(message, nested); + } + + public IncorrectPersistentClassException(String message) { + super(message); + } + + public IncorrectPersistentClassException(Throwable nested) { + super(nested); + } + +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/InitMapperException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/InitMapperException.java similarity index 76% rename from src/java/org/apache/portals/graffito/jcr/exception/InitMapperException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/InitMapperException.java index d2b3973b..2640066e 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/InitMapperException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/InitMapperException.java @@ -1,56 +1,57 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** - * Occurs when it is not possible to initialise the Mapper - * - * @author Christophe Lombart - * @author Alexandru Popescu - */ -public class InitMapperException extends JcrMappingException { - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = 8845469719898820727L; - - /** - * Constructor with message. - * - * @param message the message associated to the exception - */ - public InitMapperException(String message) { - super(message); - } - - /** - * Constructor with throwable object. - * - * @param nested the associated throwable object - */ - public InitMapperException(Throwable nested) { - super(nested); - } - - /** - * Constructor with message and throwable object. - * - * @param message the message associated to the exception - * @param nested the associated throwable object - */ - public InitMapperException(String message, Throwable nested) { - super(message, nested); - } +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** + * Occurs when it is not possible to initialise the Mapper + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class InitMapperException extends JcrMappingException { + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = 8845469719898820727L; + + /** + * Constructor with message. + * + * @param message the message associated to the exception + */ + public InitMapperException(String message) { + super(message); + } + + /** + * Constructor with throwable object. + * + * @param nested the associated throwable object + */ + public InitMapperException(Throwable nested) { + super(nested); + } + + /** + * Constructor with message and throwable object. + * + * @param message the message associated to the exception + * @param nested the associated throwable object + */ + public InitMapperException(String message, Throwable nested) { + super(message, nested); + } } \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/exception/InvalidQueryException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/InvalidQueryException.java new file mode 100644 index 00000000..79eb3902 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/InvalidQueryException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + +/** + * The InvalidQuerySyntaxException is an + * ObjectContentManagerException thrown if the query of the + * {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)} + * is invalid. This exception actually wraps a standard JCR + * javax.jcr.InvalidQueryException to make it an unchecked + * exception. The cause of this exception will always be the original + * InvalidQueryException and the message will always be the + * original exception's message. + */ +public class InvalidQueryException extends ObjectContentManagerException { + + /** + * Create an exception wrapping the given checked JCR exception + * + * @param cause The wrapped JCR InvalidQueryException + */ + public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) { + super(cause.getMessage(), cause); + } +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/JcrMappingException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/JcrMappingException.java similarity index 73% rename from src/java/org/apache/portals/graffito/jcr/exception/JcrMappingException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/JcrMappingException.java index 9918dfbb..71566f2f 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/JcrMappingException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/JcrMappingException.java @@ -1,59 +1,60 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** - * - * Base class of all runtime exceptions used in the JCR mapping. - * - * @author Christophe Lombart - * @author Alexandru Popescu - */ - -public class JcrMappingException extends NestableRuntimeException { - - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = -5237713309666840905L; - - /** - * Constructor with message. - * - * @param message the message associated to the exception - */ - public JcrMappingException(String message) { - super(message); - } - - /** - * Constructor with throwable object. - * - * @param nested the associated throwable object - */ - public JcrMappingException(Throwable nested) { - super(nested); - } - - /** - * Constructor with message and throwable object. - * - * @param message the message associated to the exception - * @param nested the associated throwable object - */ - public JcrMappingException(String message, Throwable nested) { - super(message, nested); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** + * + * Base class of all runtime exceptions used in the JCR mapping. + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ + +public class JcrMappingException extends RuntimeException { + + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = -5237713309666840905L; + + /** + * Constructor with message. + * + * @param message the message associated to the exception + */ + public JcrMappingException(String message) { + super(message); + } + + /** + * Constructor with throwable object. + * + * @param nested the associated throwable object + */ + public JcrMappingException(Throwable nested) { + super(nested); + } + + /** + * Constructor with message and throwable object. + * + * @param message the message associated to the exception + * @param nested the associated throwable object + */ + public JcrMappingException(String message, Throwable nested) { + super(message, nested); + } +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/LockedException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/LockedException.java similarity index 65% rename from src/java/org/apache/portals/graffito/jcr/exception/LockedException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/LockedException.java index 9aa915f2..a6640fb0 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/LockedException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/LockedException.java @@ -1,23 +1,24 @@ /* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.portals.graffito.jcr.exception; +package org.apache.jackrabbit.ocm.exception; /** - * Throwed if a path is locked and a operation cannot be performed - * + * Throwed if a path is locked and a operation cannot be performed + * * @author markoc */ @@ -34,7 +35,7 @@ public LockedException(String lockOwner, String lockedNodePath) { } /** - * + * * @return The JCR Lock Owner */ public String getLockOwner() { @@ -42,8 +43,8 @@ public String getLockOwner() { } /** - * - * @return The JCR locked node path + * + * @return The JCR locked node path */ public String getLockedNodePath() { return lockedNodePath; diff --git a/src/main/java/org/apache/jackrabbit/ocm/exception/LockingException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/LockingException.java new file mode 100644 index 00000000..414e6cf7 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/LockingException.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + +/** + * Base exception for all exceptions related to JCR Locking feature. + * + * @author markoc + */ +abstract public class LockingException extends ObjectContentManagerException { +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/PersistenceException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/ObjectContentManagerException.java similarity index 63% rename from src/java/org/apache/portals/graffito/jcr/exception/PersistenceException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/ObjectContentManagerException.java index a25469e3..07e2d734 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/PersistenceException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/ObjectContentManagerException.java @@ -1,62 +1,63 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** - * Occurs when it is not possible to persist an object - * - * @author Christophe Lombart - * @author Alexandru Popescu - */ -public class PersistenceException extends NestableRuntimeException { - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = -643089296035094427L; - - /** - * Not intended for usage. - */ - protected PersistenceException() { - } - - /** - * Constructor with message. - * - * @param message the message associated to the exception - */ - public PersistenceException(String message) { - super(message); - } - - /** - * Constructor with throwable object. - * - * @param nested the associated throwable object - */ - public PersistenceException(Throwable nested) { - super(nested); - } - - /** - * Constructor with message and throwable object. - * - * @param message the message associated to the exception - * @param nested the associated throwable object - */ - public PersistenceException(String message, Throwable nested) { - super(message, nested); - } +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** + * Occurs when it is not possible to persist an object + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class ObjectContentManagerException extends RuntimeException { + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = -643089296035094427L; + + /** + * Not intended for usage. + */ + protected ObjectContentManagerException() { + } + + /** + * Constructor with message. + * + * @param message the message associated to the exception + */ + public ObjectContentManagerException(String message) { + super(message); + } + + /** + * Constructor with throwable object. + * + * @param nested the associated throwable object + */ + public ObjectContentManagerException(Throwable nested) { + super(nested); + } + + /** + * Constructor with message and throwable object. + * + * @param message the message associated to the exception + * @param nested the associated throwable object + */ + public ObjectContentManagerException(String message, Throwable nested) { + super(message, nested); + } } \ No newline at end of file diff --git a/src/java/org/apache/portals/graffito/jcr/exception/RepositoryException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/RepositoryException.java similarity index 75% rename from src/java/org/apache/portals/graffito/jcr/exception/RepositoryException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/RepositoryException.java index b5c9f2d7..22bc0f62 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/RepositoryException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/RepositoryException.java @@ -1,63 +1,64 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** - * Occurs when it is not possible to manage the JCR repository (register, login, ...) - * - * @author Christophe Lombart - * @author Alexandru Popescu - */ -public class RepositoryException extends NestableRuntimeException { - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = 910346108378604638L; - - /** - * No-arg constructor used by markup exceptions. - */ - protected RepositoryException() { - } - - /** - * Constructor with message. - * - * @param message the message associated to the exception - */ - public RepositoryException(String message) { - super(message); - } - - /** - * Constructor with throwable object. - * - * @param nested the associated throwable object - */ - public RepositoryException(Throwable nested) { - super(nested); - } - - /** - * Constructor with message and throwable object. - * - * @param message the message associated to the exception - * @param nested the associated throwable object - */ - public RepositoryException(String message, Throwable nested) { - super(message, nested); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** + * Occurs when it is not possible to manage the JCR repository (register, login, ...) + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class RepositoryException extends RuntimeException { + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = 910346108378604638L; + + /** + * No-arg constructor used by markup exceptions. + */ + protected RepositoryException() { + } + + /** + * Constructor with message. + * + * @param message the message associated to the exception + */ + public RepositoryException(String message) { + super(message); + } + + /** + * Constructor with throwable object. + * + * @param nested the associated throwable object + */ + public RepositoryException(Throwable nested) { + super(nested); + } + + /** + * Constructor with message and throwable object. + * + * @param message the message associated to the exception + * @param nested the associated throwable object + */ + public RepositoryException(String message, Throwable nested) { + super(message, nested); + } + +} diff --git a/src/java/org/apache/portals/graffito/jcr/exception/VersionException.java b/src/main/java/org/apache/jackrabbit/ocm/exception/VersionException.java similarity index 76% rename from src/java/org/apache/portals/graffito/jcr/exception/VersionException.java rename to src/main/java/org/apache/jackrabbit/ocm/exception/VersionException.java index 67a70521..4e9d0830 100644 --- a/src/java/org/apache/portals/graffito/jcr/exception/VersionException.java +++ b/src/main/java/org/apache/jackrabbit/ocm/exception/VersionException.java @@ -1,58 +1,59 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.exception; - - -/** - * Occurs when it is not possible to read information on version or manage versions - * - * @author Christophe Lombart - * @author Alexandru Popescu - */ -public class VersionException extends RepositoryException { - - /** Use serialVersionUID for interoperability. */ - private final static long serialVersionUID = -7727568152521484252L; - - /** - * Constructor with message. - * - * @param message the message associated to the exception - */ - public VersionException(String message) { - super(message); - } - - /** - * Constructor with throwable object. - * - * @param nested the associated throwable object - */ - public VersionException(Throwable nested) { - super(nested); - } - - /** - * Constructor with message and throwable object. - * - * @param message the message associated to the exception - * @param nested the associated throwable object - */ - public VersionException(String message, Throwable nested) { - super(message, nested); - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.exception; + + +/** + * Occurs when it is not possible to read information on version or manage versions + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class VersionException extends RepositoryException { + + /** Use serialVersionUID for interoperability. */ + private final static long serialVersionUID = -7727568152521484252L; + + /** + * Constructor with message. + * + * @param message the message associated to the exception + */ + public VersionException(String message) { + super(message); + } + + /** + * Constructor with throwable object. + * + * @param nested the associated throwable object + */ + public VersionException(Throwable nested) { + super(nested); + } + + /** + * Constructor with message and throwable object. + * + * @param message the message associated to the exception + * @param nested the associated throwable object + */ + public VersionException(String message, Throwable nested) { + super(message, nested); + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/lock/Lock.java b/src/main/java/org/apache/jackrabbit/ocm/lock/Lock.java new file mode 100644 index 00000000..671b097a --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/lock/Lock.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.lock; + +import javax.jcr.Node; + +import org.apache.jackrabbit.ocm.exception.RepositoryException; + +/** + * Wrapper class for a JCR Lock object + * + * @author Lombart Christophe + * + */ +public class Lock +{ + + private javax.jcr.lock.Lock lock; + + public Lock(javax.jcr.lock.Lock lock) + { + this.lock = lock; + } + + public String getLockOwner() { + return lock.getLockOwner(); + } + + public String getLockToken() { + return lock.getLockToken(); + } + + public Node getNode() { + return lock.getNode(); + } + + public boolean isDeep() { + return lock.isDeep(); + } + + public boolean isLive() { + try + { + return lock.isLive(); + } + catch (javax.jcr.RepositoryException e) + { + throw new RepositoryException(e); + } + } + + public boolean isSessionScoped() { + return lock.isSessionScoped(); + } + + public void refresh() { + try + { + lock.refresh(); + } + catch (javax.jcr.RepositoryException e) + { + throw new RepositoryException(e); + } + + } + + +} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/CustomNodeTypeCreator.java b/src/main/java/org/apache/jackrabbit/ocm/manager/CustomNodeTypeCreator.java similarity index 57% rename from src/java/org/apache/portals/graffito/jcr/persistence/CustomNodeTypeCreator.java rename to src/main/java/org/apache/jackrabbit/ocm/manager/CustomNodeTypeCreator.java index efdf30cc..daf9018f 100644 --- a/src/java/org/apache/portals/graffito/jcr/persistence/CustomNodeTypeCreator.java +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/CustomNodeTypeCreator.java @@ -1,22 +1,23 @@ /* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.portals.graffito.jcr.persistence; +package org.apache.jackrabbit.ocm.manager; -import org.apache.portals.graffito.jcr.exception.CustomNodeTypeCreationException; -import org.apache.portals.graffito.jcr.persistence.impl.PersistenceManagerImpl; +import org.apache.jackrabbit.ocm.exception.CustomNodeTypeCreationException; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; /** Interface for custom node type creator implementations. * @@ -27,21 +28,21 @@ public interface CustomNodeTypeCreator { /** This method is supposed to create custom node types on repository * setup. - * - * @throws org.apache.portals.graffito.jcr.exception.CustomNodeTypeCreationException - * @return true/false True if custom node type creation succeeded + * + * @throws org.apache.jackrabbit.ocm.exception.CustomNodeTypeCreationException + * @return true/false True if custom node type creation succeeded */ boolean createInitialJcrCustomNodeTypes() throws CustomNodeTypeCreationException; /** Method to add a jcr custom node type to an existing jcr repository. - * - * @throws org.apache.portals.graffito.jcr.exception.CustomNodeTypeCreationException + * + * @throws org.apache.jackrabbit.ocm.exception.CustomNodeTypeCreationException * @return true/false True if custom node type creation succeeded */ boolean addJcrCustomNodeType() throws CustomNodeTypeCreationException; - + /** Jcr session to be injected into implementation. * @param jcrSession JcrSession */ - void setJcrSession(PersistenceManagerImpl jcrSession); + void setJcrSession(ObjectContentManagerImpl jcrSession); } diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/ManagerConstant.java b/src/main/java/org/apache/jackrabbit/ocm/manager/ManagerConstant.java new file mode 100644 index 00000000..ad211dbc --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/ManagerConstant.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager; + + + +/** + * + * General Object Content Manager Constants use in several classes + * + * @author Lombart Christophe + * + */ +public interface ManagerConstant +{ + public static final String NT_UNSTRUCTURED = "nt:unstructured"; + public static final String DISCRIMINATOR_NODE_TYPE = "ocm:discriminator"; + public static final String DISCRIMINATOR_CLASS_NAME_PROPERTY = "ocm_classname"; + + + public static final String FROZEN_NODE_TYPE = "nt:frozenNode"; + public static final String FROZEN_PRIMARY_TYPE_PROPERTY = "jcr:frozenPrimaryType"; + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/ObjectContentManager.java b/src/main/java/org/apache/jackrabbit/ocm/manager/ObjectContentManager.java new file mode 100644 index 00000000..e42e0d74 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/ObjectContentManager.java @@ -0,0 +1,559 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager; + +import java.util.Collection; +import java.util.Iterator; + +import javax.jcr.NodeIterator; +import javax.jcr.Session; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.IllegalUnlockException; +import org.apache.jackrabbit.ocm.exception.LockedException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.lock.Lock; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.version.Version; +import org.apache.jackrabbit.ocm.version.VersionIterator; + +/** + * The object content manager encapsulates a JCR session. This is the main + * component used to manage objects into the JCR repository. + * + * @author Sandro Boehme + * @author Lombart + * Christophe + * + */ +public interface ObjectContentManager { + + /** + * Check if an object exists + * + * @param path + * the object path + * @return true if the item exists + * @throws ObjectContentManagerException + * when it is not possible to check if the item exist + */ + public boolean objectExists(String path) + throws ObjectContentManagerException; + + /** + * Can this object content manager insert, update, delete, ... that type? + * + * @param clazz + * class for question + * @return true if the class is persistence + */ + boolean isPersistent(Class clazz); + + /** + * Insert an object into the JCR repository + * + * @param object + * the object to add + * @throws ObjectContentManagerException + * when it is not possible to insert the object + */ + public void insert(Object object) throws ObjectContentManagerException; + + /** + * Update an object + * + * @param object + * the object to update + * @throws ObjectContentManagerException + * when it is not possible to update the object + */ + public void update(Object object) throws ObjectContentManagerException; + + /** + * Get an object from the JCR repository + * + * @param path + * the object path + * @return the object found or null + * + * @throws ObjectContentManagerException + * when it is not possible to retrieve the object + */ + public Object getObject(String path) throws ObjectContentManagerException; + + /** + * Get an object from the JCR repository + * + * @param uuid the object uuid + * @return the object found or null + * + * @throws ObjectContentManagerException + * when it is not possible to retrieve the object + */ + public Object getObjectByUuid(String uuid) + throws ObjectContentManagerException; + + /** + * Get an object from the JCR repository + * + * @param path + * the object path + * @param versionNumber + * The desired object version number + * @return the object found or null + * + * @throws ObjectContentManagerException + * when it is not possible to retrieve the object + */ + public Object getObject(String path, String versionNumber) + throws ObjectContentManagerException; + + /** + * Get an object from the JCR repository + * + * @param objectClass + * the object class + * @param path + * the object path + * @return the object found or null + * + * @throws ObjectContentManagerException + * when it is not possible to retrieve the object + */ + public Object getObject(Class objectClass, String path) + throws ObjectContentManagerException; + + /** + * Get an object from the JCR repository + * + * @param objectClass + * the object class + * @param path + * the object path + * @param versionNumber + * The desired object version number + * @return the object found or null + * + * @throws ObjectContentManagerException + * when it is not possible to retrieve the object + */ + public Object getObject(Class objectClass, String path, String versionNumber) + throws ObjectContentManagerException; + + /** + * + * @param query + * + * @return NodeIterator + */ + public NodeIterator getNodes(Query query); + + /** + * Retrieve the specified attribute for the given persistent object. this + * attribute is either a bean or a collection. This method is usefull if the + * corresponding descriptor has an autoRetrieve="false" + * + * @param object + * The persistent object + * @param attributeName + * The name of the attribute to retrieve + */ + public void retrieveMappedAttribute(Object object, String attributeName); + + /** + * Retrieve all mapped attributes for the given persistent object. + * + * @param object + * The persistent object + */ + public void retrieveAllMappedAttributes(Object object); + + /** + * Remove an object from a JCR repository + * + * @param path + * the object path + * @throws ObjectContentManagerException + * when it is not possible to remove the object + * + */ + public void remove(String path) throws ObjectContentManagerException; + + /** + * Remove an object from a JCR repository + * + * @param object + * the object to remove + * @throws ObjectContentManagerException + * when it is not possible to remove the object + * + */ + public void remove(Object object) throws ObjectContentManagerException; + + /** + * Remove all objects matching to a query + * + * @param query + * The query used to find the objects to remove + * @throws ObjectContentManagerException + * when it is not possible to remove all objects + * + */ + public void remove(Query query) throws ObjectContentManagerException; + + /** + * Retrieve an object matching to a query + * + * @param query + * The Query object used to seach the object + * @return The object found or null + * @throws ObjectContentManagerException + * when it is not possible to retrieve the object + * + */ + public Object getObject(Query query) throws ObjectContentManagerException; + + /** + * Retrieve some objects matching to a query + * + * @param query + * The query used to search the objects + * @return a collection of objects found + * @throws ObjectContentManagerException + * when it is not possible to retrieve the objects + * + */ + public Collection getObjects(Query query) + throws ObjectContentManagerException; + + /** + * Returns a list of objects (not supertypes) of that particular class which are associated to a specific path. + * This method is helpfull when same name sibling is used to create nodes. + * This would not return the objects anywhere below the denoted path. + * + * @param objectClass + * @param path Node path. + * @return a collection of object found and empty collection if there is no node for path or when objectClass is not mapped + */ + + public Collection getObjects(Class objectClass, String path) + throws ObjectContentManagerException; + + /** + * Returns a list of objects (not supertypes) of that particular class which are child nodes of a specific path. + * This would not return the objects anywhere below the immediate children of the specified path. + * + * @param objectClass + * @param path Node path. + * @return a collection of object found and empty collection if there is no node for path or when objectClass is not mapped + */ + + public Collection getChildObjects(Class objectClass, String path) + throws ObjectContentManagerException; + + + /** + * Return a list of object matching to a JCR query + * + * @param query the JCR query + * @param language the JCR Language ("XPATH" or "SQL"). + * @return + */ + public Collection getObjects(String query, String language); + + /** + * Retrieve some objects matching to a query. + * + * @param query + * The query used to seach the objects + * @return an iterator of objects found + * @throws ObjectContentManagerException + * when it is not possible to retrieve the objects + */ + public Iterator getObjectIterator(Query query) + throws ObjectContentManagerException; + + /** + * Retrieve an objects matching a query specified in a specific query + * language. This method is expected to call create a Query + * using the session's QueryManager with the given query + * exception and language parameters. + *

+ * If the query statement is syntactically invalid, given the + * language specified, an InvalidQueryException is thrown. + * The language must be a string from among those returned by + * javax.jcr.QueryManager.getSupportedQueryLanguages(); if + * it is not, then an InvalidQueryException is thrown. + * + * @param query + * The query to execute to find the objects. + * @param language + * The language in which the query is written + * + * @return An iterator of objects instances. Each entry in the iterator + * represents the mapping of a node returned by the query. If the + * query returns a node, which may not be mapped, the respective + * node is ignored. + * + * @throws org.apache.jackrabbit.ocm.exception.InvalidQueryException + * If the query is not a valid JCR Query according to the + * specified language + * @throws ObjectContentManagerException + * If an error occurrs querying for the objects. + * + * @see javax.jcr.query.QueryManager#createQuery(String, String) + * @see javax.jcr.query.QueryManager#getSupportedQueryLanguages() + */ + public Iterator getObjectIterator(String query, String language); + + /** + * Checkout - Create a new version This is only possible if the object is + * based on mix:versionable node type + * + * @param path + * The object path + * @throws VersionException + * when it is not possible to create a new version + */ + public void checkout(String path) throws VersionException; + + /** + * Checkin an object + * + * @param path + * the object path + * @throws VersionException + * when it is not possible to checkin + */ + public void checkin(String path) throws VersionException; + + /** + * Checkin an object and apply some labels to this new version Within a + * particular object path, a given label may appear a maximum of once + * + * @param path + * The object path + * @param versionLabels + * the version labels to apply to the new version + * @throws VersionException + * when it is possible to checkin + */ + public void checkin(String path, String[] versionLabels) + throws VersionException; + + /** + * Get all version labels assigned to a particular object version + * + * @param path + * the object path + * @param versionName + * the object version name (1.0, ...) + * @return a array of string (version labels) + * @throws VersionException + * when it is not to get all version labels + */ + public String[] getVersionLabels(String path, String versionName) + throws VersionException; + + /** + * Get all version labels assigned to all versions + * + * @param path + * the object path + * @return a array of string (version labels) + * @throws VersionException + * when it is not to get all version labels + */ + public String[] getAllVersionLabels(String path) throws VersionException; + + /** + * Add a new label to a particular version + * + * @param path + * the object path + * @param versionName + * the object versio name (1.0, 1.1, ...) + * @param versionLabel + * The new label to apply + * @throws VersionException + * when it is not possible to add a new version label to this + * version + */ + public void addVersionLabel(String path, String versionName, + String versionLabel) throws VersionException; + + /** + * Get all object versions + * + * @param path + * the object path + * @return a version iterator + * @throws VersionException + * when it is not possible to retrieve all versions + */ + public VersionIterator getAllVersions(String path) throws VersionException; + + /** + * Get the first object version + * + * @param path + * the object path + * @return the first version found + * @throws VersionException + * when it is not possible to get the root version + */ + public Version getRootVersion(String path) throws VersionException; + + /** + * Get the lastest object version + * + * @param path + * the object path + * @return the last version found + * @throws VersionException + * when it is not possible to get the last version + */ + public Version getBaseVersion(String path) throws VersionException; + + /** + * Get a particular version + * + * @param path + * the object path + * @param versionName + * the version name + * @return the version found or null + * @throws VersionException + * when it is not possible to retrieve this particular version + */ + public Version getVersion(String path, String versionName) + throws VersionException; + + /** + * Save all modifications made by the object content manager + * + * @throws ObjectContentManagerException + * when it is not possible to save all pending operation into + * the JCR repo + */ + public void save() throws ObjectContentManagerException; + + /** + * Close the session + * + * @throws ObjectContentManagerException + * when it is not possible to logout + */ + public void logout() throws ObjectContentManagerException; + + /** + * Lock object saved on {@param path }. + * + * @param path + * path to saved object. + * @param isDeep + * is lock deep? See JCR spec: 8.4.3 Shallow and Deep Locks + * @param isSessionScoped + * is lock session scoped? See JCR spec: Session-scoped and + * Open-scoped Locks + * @return lock - Wrapper object for a JCR lock + * + * @throws LockedException + * if path is locked (cannot lock same path again) + */ + public Lock lock(String path, boolean isDeep, boolean isSessionScoped) + throws LockedException; + + /** + * Unlock object stored on {@param path }. + * + * @param path + * path to stored object + * + * + * @param lockToken + * see JCR spec: 8.4.6 Lock Token; can be null + * + * @throws IllegalUnlockException + * throws if the current operation does not own the current lock + */ + public void unlock(String path, String lockToken) + throws IllegalUnlockException; + + /** + * Is that path locked? + * + * @param absPath + * @return true if path locked + */ + public boolean isLocked(String absPath); + + /** + * + * @return The query manager reference + */ + public QueryManager getQueryManager(); + + /** + * Refresh the underlying jcr session (see the jcr spec) + * + * @param keepChanges + */ + public void refresh(boolean keepChanges); + + /** + * Move an object + * + * @param srcPath + * path of the object to move + * @param destPath + * destination path + * + * @throws ObjectContentManagerException + */ + public void move(String srcPath, String destPath) + throws ObjectContentManagerException; + + /** + * Copy an object from scrPath to destPath. When there does not exist a node yet at + * destPath a new node will be created there if the parent {@link javax.jcr.Node} exists already. If + * the parent does not exist, an {@link ObjectContentManagerException} will be thrown + * + * If there already exists a node at destPath, we + * try to add the {@link javax.jcr.Node} from srcPath. If not possible, an {@link ObjectContentManagerException} + * will be thrown. + * + * @param srcPath + * path of the object to copy + * @param destPath + * destination path + * + * @throws ObjectContentManagerException when the copy did not succeed for example because there exists no {@link javax.jcr.Node} at + * srcPath the parent of destPath does not exist or there already exists an (incompatible) node at destPath + */ + public void copy(String srcPath, String destPath) + throws ObjectContentManagerException; + + /** + * This method returns the JCR session. The JCR session could be used to + * make some JCR specific calls. + * + * @return the associated JCR session + */ + public Session getSession(); +} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/AtomicTypeConverter.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/AtomicTypeConverter.java similarity index 54% rename from src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/AtomicTypeConverter.java rename to src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/AtomicTypeConverter.java index e52367d3..001be348 100644 --- a/src/java/org/apache/portals/graffito/jcr/persistence/atomictypeconverter/AtomicTypeConverter.java +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/AtomicTypeConverter.java @@ -1,10 +1,10 @@ /* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -15,54 +15,48 @@ * limitations under the License. */ -package org.apache.portals.graffito.jcr.persistence.atomictypeconverter; +package org.apache.jackrabbit.ocm.manager.atomictypeconverter; import javax.jcr.Value; import javax.jcr.ValueFactory; /** - * + * * AtomicTypeConverter interface. - * + * * The Object converter used atomic type converters to map atomic fields to JCR Value objects. * Amotic fields are primitive java types and their wrapper classes. - * - * - * @author Christophe Lombart * + * + * @author Christophe Lombart + * @author Alexandru Popescu */ public interface AtomicTypeConverter { - /** * Convert an object into a JCR value. - * + * + * @param valueFactory The JCR ValueFactory * @param object The object to convert * @return the corresponding JCR value - * + * */ - public Value getValue(Object object); + public Value getValue(ValueFactory valueFactory, Object object); /** * Convert a jcr property value into an object - * + * * @param value The JCR property value * @return the corresponding object */ public Object getObject(Value value); /** - * Get the string converted value + * Get the string converted value. This is mainly used to build xpath expressions + * + * @param valueFactory The JCR ValueFactory * @param object The object value - * @return The string converted value + * @return The string converted value */ - public String getStringValue(Object object); - - /** - * Set the underlying ValueFactory to be used - * when creating the Value. - * - * @param valueFactory javax.jcr.ValueFactory - */ - public void setValueFactory(ValueFactory valueFactory); + public String getXPathQueryValue(ValueFactory valueFactory, Object object); } \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/AtomicTypeConverterProvider.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/AtomicTypeConverterProvider.java new file mode 100644 index 00000000..e782f8ee --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/AtomicTypeConverterProvider.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomictypeconverter; + + +import java.util.Map; + +/** + * This interface defines a provider for accessing + * {@link org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter} + * + * @author Alexandru Popescu + */ +public interface AtomicTypeConverterProvider { + /** + * Retrieves the AtomicTypeConverter associated with a class. + * + * @param clazz a class + * @return the corresponding AtomicTypeConverter or null + * if the class has no AtomicTypeConverter associated + */ + AtomicTypeConverter getAtomicTypeConverter(Class clazz); + + /** + * Returns a map of all registered AtomicTypeConverters. + * + * @return Map + */ + Map getAtomicTypeConverters(); + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/AtomicTypeConverterProviderImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/AtomicTypeConverterProviderImpl.java new file mode 100644 index 00000000..cded2376 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/AtomicTypeConverterProviderImpl.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; + + +/** + * Implementation of {@link AtomicTypeConverterProvider}. + * + * @author Alexandru Popescu + */ +public class AtomicTypeConverterProviderImpl implements AtomicTypeConverterProvider { + protected Map m_converters; + protected Map m_converterInstances = new HashMap(); + + /** + * No-arg constructor. + */ + public AtomicTypeConverterProviderImpl() { + } + + /** + * Full constructor. + * + * @param converters a map of classes and their associated AtomicTypeConverter + * classes. + */ + public AtomicTypeConverterProviderImpl(Map converters) { + m_converters= converters; + } + + /** + * Sets the associations of classes and their AtomicTypeConverter + * classes. + * + * @param converters Map + */ + public void setAtomicTypeConvertors(Map converters) { + m_converters= converters; + } + + /** + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider#getAtomicTypeConverter(java.lang.Class) + */ + public AtomicTypeConverter getAtomicTypeConverter(Class clazz) { + AtomicTypeConverter converter= (AtomicTypeConverter) m_converterInstances.get(clazz); + if(null != converter) { + return converter; + } + Class converterClass= (Class) m_converters.get(clazz); + if(null == converterClass) { + throw new IncorrectAtomicTypeException("No registered converter for a field based on the class :'" + clazz + "'"); + } + + try { + converter= (AtomicTypeConverter) converterClass.newInstance(); + m_converterInstances.put(clazz, converter); + } + catch(Exception ex) { + throw new IncorrectAtomicTypeException( + "Cannot create converter instance from class '" + clazz + "'", ex); + + } + + return converter; + } + + /** + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider#getAtomicTypeConverters() + */ + public Map getAtomicTypeConverters() { + Map result= new HashMap(); + for(Iterator it= m_converters.keySet().iterator(); it.hasNext(); ) { + Class clazz= (Class) it.next(); + result.put(clazz, getAtomicTypeConverter(clazz)); + } + + return result; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/BinaryTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/BinaryTypeConverterImpl.java new file mode 100644 index 00000000..742aeba0 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/BinaryTypeConverterImpl.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.io.InputStream; + +import javax.jcr.Binary; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Binary Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class BinaryTypeConverterImpl implements AtomicTypeConverter +{ + + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + + Binary binaryvalue = null; + try { + binaryvalue = valueFactory.createBinary((InputStream) propValue); + } catch (RepositoryException ex) { + throw new IncorrectAtomicTypeException("Impossible to create binary value from stream!", ex); + } + if (binaryvalue == null) { + return null; + } + + return valueFactory.createValue(binaryvalue); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return value.getBinary().getStream(); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString() , e); + } + } + + public String getXPathQueryValue(ValueFactory valueFactory,Object object) + { + throw new IncorrectAtomicTypeException("Binary cannot be used in queries"); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/BooleanTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/BooleanTypeConverterImpl.java new file mode 100644 index 00000000..ccb11268 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/BooleanTypeConverterImpl.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Boolean Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class BooleanTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + boolean value = ((Boolean) propValue).booleanValue(); + return valueFactory.createValue(value); + } + + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return new Boolean(value.getBoolean()); + } + catch (Exception e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString() , e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory,Object object) + { + return ((Boolean) object).booleanValue() ? "true()" : "false()"; + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/ByteArrayTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/ByteArrayTypeConverterImpl.java new file mode 100644 index 00000000..25375f9e --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/ByteArrayTypeConverterImpl.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Byte Array Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class ByteArrayTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + InputStream ins = new ByteArrayInputStream((byte[]) propValue); + return new BinaryTypeConverterImpl().getValue(valueFactory, ins); + } + + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return inputStreamToBytes(value.getBinary().getStream()); + } + catch (Exception e) + { + throw new IncorrectAtomicTypeException("Impossible to convert a binary value." , e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + throw new IncorrectAtomicTypeException("Binary cannot be used in queries"); + } + + private byte[] inputStreamToBytes(InputStream in) throws IOException { + + ByteArrayOutputStream out = new ByteArrayOutputStream(1024); + byte[] buffer = new byte[1024]; + int len; + + while((len = in.read(buffer)) >= 0) + out.write(buffer, 0, len); + + in.close(); + out.close(); + return out.toByteArray(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/CalendarTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/CalendarTypeConverterImpl.java new file mode 100644 index 00000000..75baae8c --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/CalendarTypeConverterImpl.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.util.Calendar; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Calendar Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class CalendarTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + + return valueFactory.createValue(((Calendar) propValue).getTimeInMillis()); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(value.getLong()); + return calendar; + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + Calendar calendar = (Calendar) object; + return new Long(calendar.getTimeInMillis()).toString(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/Date2LongTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/Date2LongTypeConverterImpl.java new file mode 100644 index 00000000..0e68186f --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/Date2LongTypeConverterImpl.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.util.Date; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Util Date Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class Date2LongTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + return valueFactory.createValue(((java.util.Date) propValue).getTime()); + } + + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + long time = value.getLong(); + return new Date(time); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return new Long(((java.util.Date) object).getTime()).toString(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/DefaultAtomicTypeConverterProvider.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/DefaultAtomicTypeConverterProvider.java new file mode 100644 index 00000000..53081819 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/DefaultAtomicTypeConverterProvider.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.io.InputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + + +/** + * An AtomicTypeConverterProvider that registers by default the + * convertes available in OCM. + * + * @author Alexandru Popescu + */ +public class DefaultAtomicTypeConverterProvider extends AtomicTypeConverterProviderImpl { + /** + * No-arg constructor. + */ + public DefaultAtomicTypeConverterProvider() { + m_converters= registerDefaultAtomicTypeConverters(); + } + + /** + * Full constructor. + * + * @param converters a map of classes and their associated AtomicTypeConverter + * classes. + */ + public DefaultAtomicTypeConverterProvider(Map converters) { + this(); + m_converters.putAll(converters); + } + + /** + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.AtomicTypeConverterProviderImpl#setAtomicTypeConvertors(java.util.Map) + */ + public void setAtomicTypeConvertors(Map converters) { + m_converters.putAll(converters); + } + + protected Map registerDefaultAtomicTypeConverters() { + Map converters= new HashMap(); + + converters.put(String.class, StringTypeConverterImpl.class); + converters.put(InputStream.class, BinaryTypeConverterImpl.class); + converters.put(long.class, LongTypeConverterImpl.class); + converters.put(Long.class, LongTypeConverterImpl.class); + converters.put(int.class, IntTypeConverterImpl.class); + converters.put(Integer.class, IntTypeConverterImpl.class); + converters.put(double.class, DoubleTypeConverterImpl.class); + converters.put(Double.class, DoubleTypeConverterImpl.class); + converters.put(boolean.class, BooleanTypeConverterImpl.class); + converters.put(Boolean.class, BooleanTypeConverterImpl.class); + converters.put(Calendar.class, CalendarTypeConverterImpl.class); + converters.put(GregorianCalendar.class, CalendarTypeConverterImpl.class); + converters.put(Date.class, UtilDateTypeConverterImpl.class); + converters.put(byte[].class, ByteArrayTypeConverterImpl.class); + converters.put(Timestamp.class, TimestampTypeConverterImpl.class); + + return converters; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/DoubleTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/DoubleTypeConverterImpl.java new file mode 100644 index 00000000..393913e0 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/DoubleTypeConverterImpl.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Double Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class DoubleTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + + double value = ((Double) propValue).doubleValue(); + return valueFactory.createValue(value); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + double beanPropValue = value.getDouble(); + return new Double(beanPropValue); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return object.toString(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/IntTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/IntTypeConverterImpl.java new file mode 100644 index 00000000..e5199e5a --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/IntTypeConverterImpl.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Int Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class IntTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + long value = ((Integer) propValue).intValue(); + return valueFactory.createValue(value); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + int beanPropValue = (int) value.getLong(); + return new Integer(beanPropValue); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return object.toString(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/LongTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/LongTypeConverterImpl.java new file mode 100644 index 00000000..89fcf5f1 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/LongTypeConverterImpl.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Long Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class LongTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + + long value = ((Long) propValue).longValue(); + return valueFactory.createValue(value); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + long beanPropValue = value.getLong(); + return new Long(beanPropValue); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return object.toString(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/NameTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/NameTypeConverterImpl.java new file mode 100644 index 00000000..fbc4c47c --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/NameTypeConverterImpl.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Name Type Converter + * + * @author Christophe Lombart + * + */ +public class NameTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + try + { + if (propValue == null) + { + return null; + } + return valueFactory.createValue((String) propValue, PropertyType.NAME); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + propValue.toString(), e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return value.getString(); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return "'" + object.toString() + "'"; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/NullTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/NullTypeConverterImpl.java new file mode 100644 index 00000000..33a08af5 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/NullTypeConverterImpl.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + + +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Double Type Converter + * + * @author Alexandru Popescu + */ +public class NullTypeConverterImpl implements AtomicTypeConverter { + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) { + return null; + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) { + return null; + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) { + return null; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/PathTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/PathTypeConverterImpl.java new file mode 100644 index 00000000..d36a07a2 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/PathTypeConverterImpl.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Name Type Converter + * + * @author Christophe Lombart + * + */ +public class PathTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + try + { + if (propValue == null) + { + return null; + } + return valueFactory.createValue((String) propValue, PropertyType.PATH); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value into a path property : " + propValue.toString() + ". Check if it is a valid path.", e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return value.getString(); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the path into a string", e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return "'" + object.toString() + "'"; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/ReferenceTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/ReferenceTypeConverterImpl.java new file mode 100644 index 00000000..9d218387 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/ReferenceTypeConverterImpl.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Reference Type Converter(java string attribute into a JCR property based on the REFERENCE type) + * + * + * @author Christophe Lombart + * + */ +public class ReferenceTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + try + { + if (propValue == null) + { + return null; + } + return valueFactory.createValue((String) propValue, PropertyType.REFERENCE); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value into a reference property : " + propValue.toString() + ". Check if it is a correct uuid", e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return value.getString(); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the uuid into a string ", e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return "'" + object.toString() + "'"; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/StringTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/StringTypeConverterImpl.java new file mode 100644 index 00000000..9242e68f --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/StringTypeConverterImpl.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * String Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class StringTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + return valueFactory.createValue((String) propValue); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + return value.getString(); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return "'" + object.toString() + "'"; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/TimestampTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/TimestampTypeConverterImpl.java new file mode 100644 index 00000000..f624daac --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/TimestampTypeConverterImpl.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.sql.Timestamp; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Timestamp Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class TimestampTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + return null; + long value = ((Timestamp) propValue).getTime(); + return valueFactory.createValue(value); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + long beanPropValue = value.getLong(); + return new Timestamp(beanPropValue); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return new Long(((Timestamp) object).getTime()).toString(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/UndefinedTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/UndefinedTypeConverterImpl.java new file mode 100644 index 00000000..88e83069 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/UndefinedTypeConverterImpl.java @@ -0,0 +1,177 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.io.InputStream; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * + * Undefined Type Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + * @author : Boni Gopalan + */ +public class UndefinedTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + + + public Value getValue(ValueFactory valueFactory, Object propValue) + { + + if (propValue == null) + { + return null; + } + + if (propValue instanceof String ) + { + return valueFactory.createValue((String) propValue); + } + + if (propValue instanceof InputStream) + { + return new BinaryTypeConverterImpl().getValue(valueFactory, propValue); + } + + if ((propValue instanceof Long || propValue instanceof Integer)) + { + return valueFactory.createValue(((Number) propValue).longValue()); + } + + if (propValue instanceof Double ) + { + return valueFactory.createValue(((Double) propValue).doubleValue()); + } + + if (propValue instanceof Boolean ) + { + return valueFactory.createValue(((Boolean) propValue).booleanValue()); + } + + if (propValue instanceof Calendar ) + { + + return valueFactory.createValue((Calendar) propValue); + } + + if (propValue instanceof GregorianCalendar ) + { + return valueFactory.createValue((GregorianCalendar) propValue); + } + + + if (propValue instanceof Date ) + { + Calendar calendar = Calendar.getInstance(); + calendar.setTime((Date) propValue); + return valueFactory.createValue(calendar); + } + + throw new IncorrectAtomicTypeException("Impossible to convert the value - property type not found"); + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + + if (value.getType() == PropertyType.STRING ) + { + return value.getString(); + } + + if (value.getType() == PropertyType.DATE) + { + return value.getDate(); + } + + if (value.getType() == PropertyType.BINARY) + { + return value.getBinary().getStream(); + } + + if (value.getType() == PropertyType.DOUBLE) + { + return new Double(value.getDouble()); + } + + if (value.getType() == PropertyType.LONG) + { + return new Long(value.getLong()); + } + + if (value.getType() == PropertyType.BOOLEAN) + { + return new Boolean(value.getBoolean()); + } + + if (value.getType() == PropertyType.NAME) + { + return value.getString(); + } + + if (value.getType() == PropertyType.PATH) + { + return value.getString(); + } + + if (value.getType() == PropertyType.REFERENCE || value.getType() == PropertyType.WEAKREFERENCE) + { + return value.getString(); + } + + throw new IncorrectAtomicTypeException("Impossible to create the value object - unsupported class"); + + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + return "'" + object.toString() + "'"; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/UtilDateTypeConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/UtilDateTypeConverterImpl.java new file mode 100644 index 00000000..766a362b --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/atomictypeconverter/impl/UtilDateTypeConverterImpl.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl; + +import java.util.Calendar; +import java.util.Date; + +import javax.jcr.RepositoryException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * Util Date Converter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class UtilDateTypeConverterImpl implements AtomicTypeConverter +{ + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(java.lang.Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + Calendar calendar = Calendar.getInstance(); + calendar.setTime((Date) propValue); + return valueFactory.createValue(calendar); + } + + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + Calendar calendar = value.getDate(); + return calendar.getTime(); + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString(), e); + } + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getStringValue(java.lang.Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + try + { + Calendar calendar = Calendar.getInstance(); + + calendar.setTime((Date) object); + + return "xs:dateTime('" + valueFactory.createValue(calendar).getString() + "')"; + + } + catch (RepositoryException e) + { + throw new IncorrectAtomicTypeException("Impossible to get the sting value ", e); + } + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/BeanConverter.java b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/BeanConverter.java new file mode 100644 index 00000000..6ef45f34 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/BeanConverter.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter; + + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ParentBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; + +/** + * Interface describing a custom bean converter. + * + * @author Alexandru Popescu + */ +public interface BeanConverter { + + + /** + * Insert the object. + * + * @param session the JCR session + * @param parentNode The node which will contain the converter bean + * @param beanDescriptor The bean descriptor + * @param beanClassDescriptor the Class Descriptor associated to the bean to insert + * @param bean the bean to convert( insert into the JCR structure) + * @param parentClassDescriptor The Class Descriptor associated to the parent object + * @param parent the object which will contain the bean to convert + * + * @throws ObjectContentManagerException thrown in case the insert fails; marks a failure due to logic of + * the insert (parent node cannot be accessed, the insert fails, etc.) + * @throws RepositoryException thrown in case the underlying repository has thrown a + * javax.jcr.RepositoryException that is not possible to be handled or + * wrapped in ObjectContentManagerException; marks a repository failure + * @throws JcrMappingException throws in case the mapping of the bean is not correct + */ + void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object bean, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException; + + /** + * Update repository from bean values. + * + * @param session the JCR session + * @param parentNode The node which will contain the converter bean + * @param beanDescriptor The bean descriptor + * @param beanClassDescriptor the Class Descriptor associated to the bean to update + * @param bean the bean to convert( insert into the JCR structure) + * @param parentClassDescriptor The Class Descriptor associated to the parent object + * @param parent the object which will contain the bean to convert + * + * @throws ObjectContentManagerException thrown in case the update fails; marks a failure due to logic + * of update (parent node cannot be accessed, the update fails, etc.) + * @throws RepositoryException thrown in case the underlying repository has thrown a + * javax.jcr.RepositoryException that is not possible to be handled or + * wrapped in ObjectContentManagerException; marks a repository failure + * @throws JcrMappingException throws in case the mapping of the bean is not correct + */ + void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object bean, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException; + + /** + * Retrieve a bean from the repository. + * + * @param session the JCR session + * @param parentNode The parent node + * @param beanDescriptor The bean descriptor + * @param beanClassDescriptor the Class Descriptor associated to the bean to insert + * @param beanClass The bean Class + * @param parent The parent which contain the bean to retrieve + * + * @throws ObjectContentManagerException thrown in case the bean cannot be retrieved or initialized; + * marks a failure due to logic of retrieval + * @throws RepositoryException thrown in case the underlying repository has thrown a + * javax.jcr.RepositoryException that is not possible to be handled or + * wrapped in ObjectContentManagerException; marks a repository failure + * @throws JcrMappingException throws in case the mapping of the bean is not correct + */ + Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException; + + + /** + * Remove the bean from the repository. + * + * @param session the JCR session + * @param parentNode The node which will contain the converter bean + * @param beanDescriptor The bean descriptor + * @param beanClassDescriptor the Class Descriptor associated to the bean to update + * @param bean the bean to convert( insert into the JCR structure) + * @param parentClassDescriptor The Class Descriptor associated to the parent object + * @param parent the object which contains the bean to convert + * + * @throws ObjectContentManagerException thrown in case the bean cannot be removed; + * marks a failure due to logic of removal + * @throws RepositoryException thrown in case the underlying repository has thrown a + * javax.jcr.RepositoryException that is not possible to be handled or + * wrapped in ObjectContentManagerException; marks a repository failure + * @throws JcrMappingException throws in case the mapping of the bean is not correct + */ + void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object bean, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException; + + /** + * Get the bean path. + * + * When the bean is mapped to a subnode, the bean path is the parent node path + the jcrname of the current bean. + * Sometime a BeanConverter can be used to access to a bean which is not mapped to a subnode. In this case, + * another implementation can be provided in this method getPath. {@link ParentBeanConverterImpl} is a good example. + * + * @param session the JCR session + * @param beanDescriptor The descriptor of the bean to convert + * @param parentNode the node which contain this bean (its corresponfing subnode) + * @return the bean path + * + * @throws RepositoryException thrown in case the underlying repository has thrown a + * javax.jcr.RepositoryException that is not possible to be handled or + * wrapped in ObjectContentManagerException; marks a repository failure + * + */ + String getPath(Session session, BeanDescriptor beanDescriptor, Node parentNode) + throws ObjectContentManagerException; + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/AbstractBeanConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/AbstractBeanConverterImpl.java new file mode 100644 index 00000000..59d32ea7 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/AbstractBeanConverterImpl.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +/** + * + * Abstract Bean Converter Class + * + * @author Lombart Christophe + * + */ +public abstract class AbstractBeanConverterImpl implements BeanConverter { + + protected ObjectConverter objectConverter; + protected Mapper mapper; + protected AtomicTypeConverterProvider atomicTypeConverterProvider; + + public AbstractBeanConverterImpl(Mapper mapper, ObjectConverter objectConverter, AtomicTypeConverterProvider atomicTypeConverterProvider) + { + this.mapper = mapper; + this.objectConverter = objectConverter; + this.atomicTypeConverterProvider = atomicTypeConverterProvider; + } + + /** + * + * Default implementation for many BeanConverter. This method can be overridden in specific BeanConverter + * + */ + public String getPath(Session session, BeanDescriptor beanDescriptor, Node parentNode) + throws ObjectContentManagerException + { + return ObjectContentManagerUtil.getPath(session, beanDescriptor, parentNode); + } + + public abstract void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException; + + public abstract void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException; + + public abstract Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) + throws ObjectContentManagerException, RepositoryException,JcrMappingException ; + + public abstract void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException ; +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/DefaultBeanConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/DefaultBeanConverterImpl.java new file mode 100644 index 00000000..1395173e --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/DefaultBeanConverterImpl.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Default Bean Converter + * + * + * @author Lombart Christophe + * + */ +public class DefaultBeanConverterImpl extends AbstractBeanConverterImpl implements BeanConverter { + + private final static Logger log = LoggerFactory.getLogger(DefaultBeanConverterImpl.class); + + public DefaultBeanConverterImpl(Mapper mapper, ObjectConverter objectConverter, AtomicTypeConverterProvider atomicTypeConverterProvider) + { + super(mapper, objectConverter, atomicTypeConverterProvider); + } + + public void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException + { + objectConverter.insert(session, parentNode, beanDescriptor.getJcrName(), object); + } + + public void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException + { + try + { + String jcrNodeName = beanDescriptor.getJcrName(); + if (parentNode.hasNode(jcrNodeName)) + { + objectConverter.update(session, parentNode, beanDescriptor.getJcrName() , object); + } + else + { + objectConverter.insert(session, parentNode, beanDescriptor.getJcrName() , object); + } + } + catch (javax.jcr.RepositoryException e) + { + throw new RepositoryException(e); + } + } + + public Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) + throws ObjectContentManagerException, RepositoryException,JcrMappingException + { + return objectConverter.getObject(session, beanClass, this.getPath(session, beanDescriptor, parentNode)); + + } + + public void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException + { + try { + if (parentNode.hasNode(beanDescriptor.getJcrName())) + { + parentNode.getNode(beanDescriptor.getJcrName()).remove(); + } + + } catch (javax.jcr.RepositoryException e) { + + throw new RepositoryException(e); + } + + } + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/InlineBeanConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/InlineBeanConverterImpl.java new file mode 100644 index 00000000..10c004a3 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/InlineBeanConverterImpl.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.impl.SimpleFieldsHelper; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +/** + * + * Bean converter used to map some node properties into one nested bean field. + * The corresponding bean field is not associated to a subnode. + * + * @author Lombart Christophe + * + */ +public class InlineBeanConverterImpl extends AbstractBeanConverterImpl implements BeanConverter { + + SimpleFieldsHelper simpleFieldsHelper; + + public InlineBeanConverterImpl(Mapper mapper, ObjectConverter objectConverter, AtomicTypeConverterProvider atomicTypeConverterProvider) + { + super(mapper, objectConverter, atomicTypeConverterProvider); + this.simpleFieldsHelper = new SimpleFieldsHelper(atomicTypeConverterProvider); + } + + public void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + + simpleFieldsHelper.storeSimpleFields(session, object, beanClassDescriptor, parentNode); + } + + public void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + simpleFieldsHelper.storeSimpleFields(session, object, beanClassDescriptor, parentNode); + } + + public Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object bean) + throws ObjectContentManagerException, RepositoryException,JcrMappingException { + + return simpleFieldsHelper.retrieveSimpleFields(session, beanClassDescriptor, parentNode, bean); + + } + + public void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + + simpleFieldsHelper.storeSimpleFields(session, object, beanClassDescriptor, parentNode); + } + + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/ParentBeanConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/ParentBeanConverterImpl.java new file mode 100644 index 00000000..b2af9dfb --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/ParentBeanConverterImpl.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Bean converter used to access to the parent object. + * the mixin type referenceable is not mandatory for the node matching to the parent object. + * + * + * @author Lombart Christophe + * + */ +public class ParentBeanConverterImpl extends AbstractBeanConverterImpl implements BeanConverter { + + private final static Logger log = LoggerFactory.getLogger(ParentBeanConverterImpl.class); + + public ParentBeanConverterImpl(Mapper mapper, ObjectConverter objectConverter, AtomicTypeConverterProvider atomicTypeConverterProvider) + { + super(mapper, objectConverter, atomicTypeConverterProvider); + } + + public void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + } + + public void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + } + + public Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) + throws ObjectContentManagerException, RepositoryException,JcrMappingException { + try + { + Node grandParentNode = parentNode.getParent(); + if (grandParentNode.getPath().equals("/")) + { + return null; + } + return objectConverter.getObject(session, grandParentNode.getPath()); + + } + catch (javax.jcr.RepositoryException e) + { + throw new RepositoryException(e); + } + + } + + public void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + + } + + /** + * + * Default implementation for many BeanConverter. This method can be overridden in specific BeanConverter + * + */ + public String getPath(Session session, BeanDescriptor beanDescriptor, Node parentNode) + throws ObjectContentManagerException + { + try + { + if (parentNode != null) + { + + return parentNode.getParent().getPath(); + } + else + { + return null; + } + } + catch (javax.jcr.RepositoryException e) + { + throw new RepositoryException(e); + } + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/ReferenceBeanConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/ReferenceBeanConverterImpl.java new file mode 100644 index 00000000..8bfdb71b --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/beanconverter/impl/ReferenceBeanConverterImpl.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter.impl; + +import javax.jcr.Node; +import javax.jcr.PropertyType; +import javax.jcr.Session; +import javax.jcr.Value; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Map a bean attribute into a reference jcr property. It is not possible to update direclty the referenced bean. + * Only the corresponding uuid can be updated in the main object. The modifications on the referenced bean attributes are ignored + * + * + * @author Lombart Christophe + * + */ +public class ReferenceBeanConverterImpl extends AbstractBeanConverterImpl implements BeanConverter { + + private final static Logger log = LoggerFactory.getLogger(ReferenceBeanConverterImpl.class); + + public ReferenceBeanConverterImpl(Mapper mapper, ObjectConverter objectConverter, AtomicTypeConverterProvider atomicTypeConverterProvider) + { + super(mapper, objectConverter, atomicTypeConverterProvider); + } + + public void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException + { + updateReferenceProperty(parentNode, beanDescriptor, beanClassDescriptor, object); + + } + + public void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException + { + updateReferenceProperty(parentNode, beanDescriptor, beanClassDescriptor, object); + } + + public Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) + throws ObjectContentManagerException, RepositoryException,JcrMappingException + { + try { + String uuid = parentNode.getProperty(beanDescriptor.getJcrName()).getString(); + String path = session.getNodeByIdentifier(uuid).getPath(); + + return objectConverter.getObject(session, path); + } catch (Exception e) { + return null; + + } + + } + + public void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException + { + updateReferenceProperty(parentNode, beanDescriptor, beanClassDescriptor, null); + } + + private void updateReferenceProperty(Node parentNode, BeanDescriptor beanDescriptor,ClassDescriptor beanClassDescriptor, Object object) { + try { + if (object == null) + { + parentNode.setProperty(beanDescriptor.getJcrName(), (Value) null); + } + + FieldDescriptor fieldDescriptor = beanClassDescriptor.getUuidFieldDescriptor(); + if (fieldDescriptor == null) + { + throw new JcrMappingException("The bean doesn't have an uuid - classdescriptor : " + beanClassDescriptor.getClassName()); + } + + String uuid = (String) ReflectionUtils.getNestedProperty(object, fieldDescriptor.getFieldName()); + parentNode.setProperty(beanDescriptor.getJcrName(), uuid, PropertyType.REFERENCE); + } catch (Exception e) { + throw new ObjectContentManagerException("Impossible to insert the bean attribute into the repository", e); + } + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/cache/ObjectCache.java b/src/main/java/org/apache/jackrabbit/ocm/manager/cache/ObjectCache.java new file mode 100644 index 00000000..5ec20ce1 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/cache/ObjectCache.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.cache; + +/** + * + * + * Interface use for an object cache. + * + * @author Lombart Christophe + * + */ +public interface ObjectCache { + + /** + * Put an object to current session's object cache + * + * @param path Path to object + * @param object Cached object + */ + void cache(String path, Object object); + + /** + * Clear current session's object cache + */ + void clear(); + + /** + * Check for object presence in the current session's object cache If the object is not in the current session's + * object cache, it is copied to current session's object cache from the global object cache. + * + * @param path Path to object + * @return true if the object is present in the current session's object cache + */ + boolean isCached(String path); + + /** + * Get the object from the current session's object cache. If the object is not in the current session's object + * cache, it is copied to current session's object cache from the global object cache. + * + * @param path Path to object + * @return Object (perhaps partially loaded), or null otherwise + */ + Object getObject(String path); + + /** + * Remove an object from the current session's object cache. Also remove the object and all its subobjects from the + * global object cache. + * + * @param path Path to object + */ + void evict(String path); + + /** + * Transfer a fully loaded object into the global object cache. + * + * @param path Path to object + * @param object A fully loaded object + */ + void ready(String path, Object object); + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/cache/impl/RequestObjectCacheImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/cache/impl/RequestObjectCacheImpl.java new file mode 100644 index 00000000..34dc4a58 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/cache/impl/RequestObjectCacheImpl.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.cache.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.jackrabbit.ocm.manager.cache.ObjectCache; + +/** + * + * This is a simple cache implementation that can be used per retrieve requests. + * This avoids to load duplicated object instance. + * + * @author Lombart Christophe + * +*/ +public class RequestObjectCacheImpl implements ObjectCache { + + private final Map alreadyCachedObjects = new HashMap(); + + public void cache(String path, Object object) { + alreadyCachedObjects.put(path, object); + } + + public void clear() { + alreadyCachedObjects.clear(); + } + + public boolean isCached(String path) { + return alreadyCachedObjects.containsKey(path); + } + + public Object getObject(String path) { + return alreadyCachedObjects.get(path); + } + + public void evict(String path) { + alreadyCachedObjects.remove(path); + } + + public void ready(String path, Object object) { + /* noop - no global cache */ + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/CollectionConverter.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/CollectionConverter.java new file mode 100644 index 00000000..28f686e3 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/CollectionConverter.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * Convert any kind of {@link ManageableObjects} into severals JCR nodes. + * + * @author Lombart Christophe + * + */ +public interface CollectionConverter +{ + + /** + * Insert/convert collection elements (a Collection or a Map) into some JCR nodes + * @param session The JCR session + * @param parentNode the node which will contains the collection element + * @param collectionDescriptor The collection descriptor + * @param objects The objects to insert + * + * @throws ObjectContentManagerException when it is not possible to insert the collection + * + */ + public void insertCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, ManageableObjects objects) throws ObjectContentManagerException; + + /** + * Update collection elements (a Collection or a Map) already present in the JCR repository + * @param session The JCR session + * @param parentNode the node which will contains the collection element + * @param collectionDescriptor The collection descriptor + * @param objects The objects to update + * + * @throws ObjectContentManagerException when it is not possible to update the collection + */ + public void updateCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, ManageableObjects objects) throws ObjectContentManagerException; + + /** + * Get a {@link ManageableObjects} from the JCR repository + * @param session The JCR session + * @param parentNode the node which contains the collection element + * @param collectionDescriptor The collection descriptor + * @param collectionFieldClass The collection class to used (ArrayList, Vector, ..) + * @return The collection or a map populates with all elements found in the JCR repository + * + * @throws ObjectContentManagerException when it is not possible to retrieve the collection + */ + public ManageableObjects getCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) throws ObjectContentManagerException; + + + /** + * Check if the collection is null. This method is mainly used in the Proxy manager to return a null value or a proxy object + * Without proxy proxy, this method is never called. + * + * @param session The JCR session + * @param parentNode the node which contains the collection element + * @param collectionDescriptor The collection descriptor + * @param collectionFieldClass The collection class to used (ArrayList, Vector, ..) + * @return true if the collection contains elements. + * + * + * @throws ObjectContentManagerException when it is not possible to retrieve the collection + */ + public boolean isNull(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) throws ObjectContentManagerException; +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableCollection.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableCollection.java new file mode 100644 index 00000000..fb78161f --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableCollection.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + + +/** + * Common interface used to persist any kind of Collection. + * + * + * @author Christophe Lombart + * + */ +public interface ManageableCollection extends ManageableObjects +{ + /** + * Add an object into this ManageableCollection + * @param object the object to add + */ + public void addObject(Object object); + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableMap.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableMap.java new file mode 100644 index 00000000..fbd7572c --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableMap.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + + +/** + * Common interface used to persist any kind of Map. + * + * + * @author Christophe Lombart + * + */ +public interface ManageableMap extends ManageableObjects +{ + /** + * Add an object into this ManageableMap + * @param key the object key + * @param object the object to add + */ + public void addObject(Object key, Object object); + + +} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/ManageableCollection.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableObjects.java similarity index 52% rename from src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/ManageableCollection.java rename to src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableObjects.java index d64ea528..77e1c109 100644 --- a/src/java/org/apache/portals/graffito/jcr/persistence/collectionconverter/ManageableCollection.java +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableObjects.java @@ -1,47 +1,46 @@ /* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - -package org.apache.portals.graffito.jcr.persistence.collectionconverter; +package org.apache.jackrabbit.ocm.manager.collectionconverter; import java.util.Iterator; -/** +/** * Common interface used to persist any kind of Collection or Map. - * + * * * @author Christophe Lombart - * + * */ -public interface ManageableCollection +public interface ManageableObjects { - /** - * Add an object into this ManageableCollection - * @param object the object to add - */ - public void addObject(Object object); - /** * @return The ManageableCollection iterator */ public Iterator getIterator(); - - /** + + /** * @return The ManageableCollection size */ public int getSize(); - - + + /** + * @return The objects managed by the underlying Collection or Map + */ + public Object getObjects(); + + } diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableObjectsUtil.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableObjectsUtil.java new file mode 100644 index 00000000..8a087206 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/ManageableObjectsUtil.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + + +import java.util.Collection; +import java.util.Map; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ManageableCollectionImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ManageableMapImpl; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; + +/** + * Utility class used to instantiate {@link ManageableObjects} + * A ManageableObjects is a Collection or a Map + * + * @author Christophe Lombart + * + */ +public class ManageableObjectsUtil { + + /** + * Instantiate a new {@link ManageableObjects} + * @param manageableObjectsClassName The manageable objects class name + * @return an emtpy created {@link ManageableObjects} + */ + public static ManageableObjects getManageableObjects(String manageableObjectsClassName) { + try { + return (ManageableObjects) ReflectionUtils.newInstance(manageableObjectsClassName); + } + catch (Exception e) { + throw new JcrMappingException("Cannot create manageable collection : " + + manageableObjectsClassName, + e); + } + } + + /** + * Instantiate a new {@link ManageableObjects} + * @param manageableObjectsClass the collection class name + * @return an emtpy created {@link ManageableCollection} + */ + + public static ManageableObjects getManageableObjects(Class manageableObjectsClass) { + try { + + // if the class is an interface, try to find the default class implementation + if (manageableObjectsClass.isInterface()) + { + + Class defaultImplementation = ReflectionUtils.getDefaultImplementation(manageableObjectsClass); + if (defaultImplementation == null) + { + throw new JcrMappingException("No default implementation for the interface " + manageableObjectsClass); + } + else + { + manageableObjectsClass = defaultImplementation; + } + } + + //if the class is implementing the Collection interface + if (ReflectionUtils.implementsInterface(manageableObjectsClass, Collection.class)) + { + return new ManageableCollectionImpl((Collection) ReflectionUtils.newInstance(manageableObjectsClass)); + } + + //if the class is implementing the Map interface + if (ReflectionUtils.implementsInterface(manageableObjectsClass, Map.class)) + { + return new ManageableMapImpl((Map) ReflectionUtils.newInstance(manageableObjectsClass)); + } + + + Object manageableObjects = manageableObjectsClass.newInstance(); + if (!(manageableObjects instanceof ManageableObjects)) { + throw new JcrMappingException("Unsupported collection type :" + + manageableObjectsClass.getName()); + } + else { + return (ManageableObjects) manageableObjects; + } + } + catch (Exception e) { + throw new JcrMappingException("Cannot create manageable objects (Collection or Map)", e); + } + } + + /** + * Convert a java Collection or a Map into a {@link ManageableObjects}. + * + * The elements of a Map should have an ID field (see the field descriptor definition). + * @param object the collection or the Map objet + * @return The converted {@link ManageableObjects} + * + */ + public static ManageableObjects getManageableObjects(Object object) { + try { + if (object == null) { + return null; + } + + if (object instanceof ManageableObjects) { + return (ManageableObjects) object; + + } + + //if the class is implementing the Collection interface + if (ReflectionUtils.implementsInterface(object.getClass(), Collection.class)) + { + return new ManageableCollectionImpl((Collection) object); + } + + //if the class is implementing the Map interface + if (ReflectionUtils.implementsInterface(object.getClass(), Map.class)) + { + return new ManageableMapImpl((Map) object); + } + + + } + catch (Exception e) { + throw new JcrMappingException("Impossible to create the manageable collection", e); + } + + throw new JcrMappingException("Unsupported collection type :" + object.getClass().getName()); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/AbstractCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/AbstractCollectionConverterImpl.java new file mode 100644 index 00000000..9f3813d2 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/AbstractCollectionConverterImpl.java @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + +import java.util.Map; + +import javax.jcr.ItemExistsException; +import javax.jcr.Node; +import javax.jcr.PathNotFoundException; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * Abstract class used for all CollectionConverter + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public abstract class AbstractCollectionConverterImpl implements CollectionConverter { + protected Map atomicTypeConverters; + protected ObjectConverter objectConverter; + protected Mapper mapper; + + /** + * Constructor + * + * @param atomicTypeConverters The atomic type converter to used + * @param objectConverter The object converter to used + * @param mapper The mapper to used + */ + public AbstractCollectionConverterImpl(Map atomicTypeConverters, ObjectConverter objectConverter, Mapper mapper) { + this.atomicTypeConverters = atomicTypeConverters; + this.objectConverter = objectConverter; + this.mapper = mapper; + } + + protected abstract void doInsertCollection(Session session, Node parentNode, CollectionDescriptor descriptor, + ManageableObjects objects) throws RepositoryException; + + protected abstract void doUpdateCollection(Session session, Node parentNode, CollectionDescriptor descriptor, + ManageableObjects objects) throws RepositoryException; + + protected abstract ManageableObjects doGetCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) throws RepositoryException; + + protected abstract boolean doIsNull(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException; + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter#insertCollection(javax.jcr.Session, javax.jcr.Node, org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection) + */ + public void insertCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, + ManageableObjects objects) { + try { + doInsertCollection(session, parentNode, collectionDescriptor, objects); + } catch (ItemExistsException iee) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName() + ". An item already exists.", iee); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName(), pnfe); + } catch (VersionException ve) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName(), ve); + } catch (ConstraintViolationException cve) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName() + ". Constraint violation.", cve); + } catch (LockException le) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName() + " on locked parent.", le); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), re); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter#updateCollection(javax.jcr.Session, javax.jcr.Node, org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection) + */ + public void updateCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, + ManageableObjects objects) { + try { + + doUpdateCollection(session, parentNode, collectionDescriptor, objects); + } catch (VersionException ve) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName(), ve); + } catch (LockException le) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName() + " on locked node", le); + } catch (ConstraintViolationException cve) { + throw new ObjectContentManagerException("Cannot insert collection field : " + collectionDescriptor.getFieldName() + + " of class " + collectionDescriptor.getClassDescriptor().getClassName() + " Constraint violation.", cve); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), re); + } + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter#getCollection(javax.jcr.Session, javax.jcr.Node, org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, java.lang.Class) + */ + public ManageableObjects getCollection(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) { + try { + return doGetCollection(session, parentNode, collectionDescriptor, collectionFieldClass); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Cannot get collection field : " + + collectionDescriptor.getFieldName() + " for " + collectionDescriptor.getClassDescriptor().getClassName(), re); + } + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter#isNull(Session, Node, CollectionDescriptor, Class) + */ + public boolean isNull(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) { + try { + return doIsNull(session, parentNode, collectionDescriptor, collectionFieldClass); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Cannot check if the collections has elements : " + + collectionDescriptor.getFieldName() + "for " + collectionDescriptor.getClassDescriptor().getClassName(), re); + } + } + protected String getCollectionJcrName(CollectionDescriptor descriptor) { + String jcrName = descriptor.getJcrName(); + + if (null == jcrName) { + throw new JcrMappingException("The JcrName attribute is not defined for the CollectionDescriptor : " + + descriptor.getFieldName()); + } + + return jcrName; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/BeanReferenceCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/BeanReferenceCollectionConverterImpl.java new file mode 100644 index 00000000..3b0bb6a9 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/BeanReferenceCollectionConverterImpl.java @@ -0,0 +1,199 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; + +/** + * Collection Mapping used to map a reference/uuid property list into a java bean collection (readonly). + * Only the uuid can be modified, not the associated object + * + * @author Christophe Lombart + * + */ +public class BeanReferenceCollectionConverterImpl extends AbstractCollectionConverterImpl { + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public BeanReferenceCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + addUuidProperties(session, parentNode, collectionDescriptor, objects); + } + + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException + { + String jcrName = getCollectionJcrName(collectionDescriptor); + + // Delete existing values + if (parentNode.hasProperty(jcrName)) { + parentNode.setProperty(jcrName, (Value[]) null); + } + + if (objects == null) { + return; + } + + addUuidProperties(session, parentNode, collectionDescriptor, objects); + + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + if (!parentNode.hasProperty(jcrName)) { + return null; + } + Property property = parentNode.getProperty(jcrName); + Value[] values = property.getValues(); + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + + // For collection of bean references, only Collections are supported + if (! (objects instanceof ManageableCollection)) + { + + throw new JcrMappingException("Impossible to retrieve the attribute " + + collectionDescriptor.getFieldName() + " in the class " + + collectionDescriptor.getClassDescriptor().getClassName() + + " because it is not a collection"); + } + + for (int i = 0; i < values.length; i++) { + String uuid = values[i].getString(); + String path = session.getNodeByIdentifier(uuid).getPath(); + Object object = objectConverter.getObject(session, path); + ((ManageableCollection) objects).addObject(object); + } + + return objects; + } + catch(Exception e) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), e); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, Class collectionFieldClass) throws RepositoryException + { + String jcrName = getCollectionJcrName(collectionDescriptor); + return ! parentNode.hasProperty(jcrName); + } + + private void addUuidProperties(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) + throws UnsupportedRepositoryOperationException, RepositoryException, VersionException, LockException, ConstraintViolationException { + try { + if (objects == null) { + return; + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + Value[] values = new Value[objects.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + Iterator collectionIterator = objects.getIterator(); + for (int i = 0; i < objects.getSize(); i++) { + Object object = collectionIterator.next(); + if (object != null) + { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(object.getClass()); + + FieldDescriptor fieldDescriptor = classDescriptor.getUuidFieldDescriptor(); + if (fieldDescriptor == null) + { + throw new JcrMappingException("The bean doesn't have an uuid - classdescriptor : " + + classDescriptor.getClassName()); + } + + String uuid = (String) ReflectionUtils.getNestedProperty(object, fieldDescriptor.getFieldName()); + values[i] = valueFactory.createValue(uuid, PropertyType.REFERENCE); + } + } + + parentNode.setProperty(jcrName, values); + } + catch(Exception e) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), e); + } + } + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/BeanReferenceMapConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/BeanReferenceMapConverterImpl.java new file mode 100644 index 00000000..07e6ac31 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/BeanReferenceMapConverterImpl.java @@ -0,0 +1,222 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; + +/** + * Map converter used to map reference/uuid property by key into a java.util.Map. + *

+ * This implementation takes for granted that the keys to the map are of type java.lang.String. + *

+ * Further development will be required to fully support Map. + * + * @author Vincent Giguere + */ +public class BeanReferenceMapConverterImpl extends AbstractCollectionConverterImpl { + + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public BeanReferenceMapConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + // For maps of bean references, only Maps are supported + if (!(objects instanceof ManageableMap)) { + + throw new JcrMappingException("Impossible to retrieve the attribute " + + collectionDescriptor.getFieldName() + " in the class " + + collectionDescriptor.getClassDescriptor().getClassName() + + " because it is not a map"); + } + + + addUuidProperties(session, parentNode, collectionDescriptor, (ManageableMap) objects); + } + + + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + // For maps of bean references, only Maps are supported + if (!(objects instanceof ManageableMap)) { + + throw new JcrMappingException("Impossible to retrieve the attribute " + + collectionDescriptor.getFieldName() + " in the class " + + collectionDescriptor.getClassDescriptor().getClassName() + + " because it is not a map"); + } + String jcrName = getCollectionJcrName(collectionDescriptor); + + // Delete existing values + if (parentNode.hasProperty(jcrName)) { + parentNode.setProperty(jcrName, (Value[]) null); + } + + if (objects == null) { + return; + } + + addUuidProperties(session, parentNode, collectionDescriptor, (ManageableMap) objects); + + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.impl.AbstractCollectionConverterImpl#doGetCollection(javax.jcr.Session, javax.jcr.Node, org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + + + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + + if (!parentNode.hasProperty(jcrName)) { + return null; + } + + Property property = parentNode.getProperty(jcrName); + Value[] values = property.getValues(); + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + + // For maps of bean references, only Maps are supported + if (!(objects instanceof ManageableMap)) { + + throw new JcrMappingException("Impossible to retrieve the attribute " + + collectionDescriptor.getFieldName() + " in the class " + + collectionDescriptor.getClassDescriptor().getClassName() + + " because it is not a map"); + } + + for (int i = 0; i < values.length; i++) { + + String encoded = values[i].getString(); + String key = MapReferenceValueEncoder.decodeKey(encoded); + String uuid = MapReferenceValueEncoder.decodeReference(encoded); + + + String path = session.getNodeByIdentifier(uuid).getPath(); + Object object = objectConverter.getObject(session, path); + ((ManageableMap) objects).addObject(key, object); + } + + return objects; + } + catch (Exception e) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), e); + } + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.impl.AbstractCollectionConverterImpl#doIsNull(javax.jcr.Session, javax.jcr.Node, org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, Node parentNode, CollectionDescriptor collectionDescriptor, Class collectionFieldClass) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + return !parentNode.hasProperty(jcrName); + } + + private void addUuidProperties(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableMap manageableMap) + throws UnsupportedRepositoryOperationException, RepositoryException, VersionException, LockException, ConstraintViolationException { + try { + if (manageableMap == null) { + return; + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + Value[] values = new Value[manageableMap.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + Map map = (Map) manageableMap.getObjects(); + Iterator keyIterator = map.keySet().iterator(); + + for (int i = 0; i < manageableMap.getSize(); i++) { + String key = (String) keyIterator.next(); + Object object = map.get(key); + if (object != null) { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(object.getClass()); + + FieldDescriptor fieldDescriptor = classDescriptor.getUuidFieldDescriptor(); + if (fieldDescriptor == null) { + throw new JcrMappingException("The bean doesn't have an uuid - classdescriptor : " + + classDescriptor.getClassName()); + } + + String uuid = (String) ReflectionUtils.getNestedProperty(object, fieldDescriptor.getFieldName()); + values[i] = valueFactory.createValue(MapReferenceValueEncoder.encodeKeyAndReference(key, uuid), PropertyType.STRING); + } + } + + parentNode.setProperty(jcrName, values); + + } + catch (Exception e) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), e); + } + } + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/DefaultCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/DefaultCollectionConverterImpl.java new file mode 100644 index 00000000..364dfb64 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/DefaultCollectionConverterImpl.java @@ -0,0 +1,394 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.jcr.ItemExistsException; +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.version.VersionException; + +import org.apache.commons.lang.StringUtils; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; + +/** + * Default Collection Mapping/convertion implementation. + * + * This collection mapping strategy maps a collection under an extra JCR node (specify by the jcrName in the CollectionDescriptor). + * It is usefull when the node type "nt:unstructured" is applied to the collection elements. By this way, it is possible + * to distinguish the collection elements from the other main object fields. + * + * If the collection element class contains an id (see the ID FieldDescriptor definition), this id value is used to build the collection element node. + * Otherwise, the element node name is a simple constant. + * + * Example - without an id attribute: + * /test (Main object containing the collection field ) + * /mycollection (extra node used to store the entire collection) + * /collection-element (node used to store the first collection element) + * /item-prop + * .... + * /collection-element (node used to store the second collection element) + * ... + * + * Example - with an id attribute: + * /test (Main object containing the collection field ) + * /mycollection (extra node used to store the entire collection) + * /aValue (id value assigned to the first element) + * /item-prop + * .... + * /anotherValue (id value assigned to the first element) + * ... + + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class DefaultCollectionConverterImpl extends AbstractCollectionConverterImpl { + + protected static final String COLLECTION_ELEMENT_NAME = "collection-element"; + + /** + * Constructor + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public DefaultCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableObjects) + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + if (objects == null) { + return; + } + + String jcrName = collectionDescriptor.getJcrName(); + + if (jcrName == null) { + throw new JcrMappingException( + "The JcrName attribute is not defined for the CollectionDescriptor : " + + collectionDescriptor.getFieldName() + " for the classdescriptor : " + collectionDescriptor.getClassDescriptor().getClassName()); + } + + Node collectionNode; + if (!StringUtils.isBlank(collectionDescriptor.getJcrType())) { + collectionNode = parentNode.addNode(jcrName, collectionDescriptor.getJcrType()); + } else { + collectionNode = parentNode.addNode(jcrName); + } + + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); + + if (objects instanceof ManageableCollection) + insertManageableCollection(session, objects, collectionNode, elementClassDescriptor, collectionDescriptor); + else + insertManageableMap(session, objects, collectionNode); + + } + + private void insertManageableCollection(Session session, + ManageableObjects objects, Node collectionNode, + ClassDescriptor elementClassDescriptor, + CollectionDescriptor collectionDescriptor) { + Iterator collectionIterator = objects.getIterator(); + while (collectionIterator.hasNext()) { + Object item = collectionIterator.next(); + String elementJcrName = null; + + // If the element object has a unique id => the element jcr node name = the id value + if (elementClassDescriptor.hasIdField()) { + String idFieldName = elementClassDescriptor.getIdFieldDescriptor() + .getFieldName(); + elementJcrName = ReflectionUtils.getNestedProperty(item, idFieldName).toString(); + } + else { + elementJcrName = collectionDescriptor.getJcrElementName(); + if (elementJcrName == null) { // use PathFormat.checkFormat() here? + elementJcrName = UUID.randomUUID().toString(); + } + } + + objectConverter.insert(session, collectionNode, elementJcrName, item); + } + } + + private void insertManageableMap(Session session, ManageableObjects objects, Node collectionNode) { + + + Map map = (Map) objects.getObjects(); + for (Object key : map.keySet()) + { + Object item = map.get(key); + objectConverter.insert(session, collectionNode, key.toString(), item); + + } + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableObjects) + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + String jcrName = getCollectionJcrName(collectionDescriptor); + boolean hasNode = parentNode.hasNode(jcrName); + // If the new value for the collection is null, drop the node matching to the collection + if (objects == null) + { + if (hasNode) + { + parentNode.getNode(jcrName).remove(); + } + return; + } + + // If there is not yet a node matching to the collection, insert the collection + if (! hasNode) + { + this.doInsertCollection(session, parentNode, collectionDescriptor, objects); + return; + } + + // update process + if (objects instanceof ManageableCollection) + updateManagableCollection(session, parentNode, collectionDescriptor, objects, jcrName); + else + updateManagableMap(session, parentNode, collectionDescriptor, objects, jcrName); + + } + + private void updateManagableCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects, String jcrName) + throws PathNotFoundException, RepositoryException, + VersionException, LockException, ConstraintViolationException, + ItemExistsException { + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); + Node collectionNode = parentNode.getNode(jcrName); + // If the collection elements have not an id, it is not possible to find the matching JCR nodes + // => delete the complete collection + if (!elementClassDescriptor.hasIdField() && !elementClassDescriptor.hasUUIdField()) { + String primaryNodeTypeName = collectionNode.getPrimaryNodeType().getName(); + collectionNode.remove(); + collectionNode = parentNode.addNode(jcrName, primaryNodeTypeName); + } + + Iterator collectionIterator = objects.getIterator(); + + Map updatedItems = new HashMap(); + List validUuidsForTheNode = new ArrayList(); + while (collectionIterator.hasNext()) { + Object item = collectionIterator.next(); + String elementJcrName = null; + + if (elementClassDescriptor.hasUUIdField()){ + elementJcrName = collectionDescriptor.getJcrElementName(); + elementJcrName = (elementJcrName == null)? COLLECTION_ELEMENT_NAME : elementJcrName; + String uuidFieldName = elementClassDescriptor.getUuidFieldDescriptor().getFieldName(); + Object objUuid = ReflectionUtils.getNestedProperty(item, uuidFieldName); + String currentItemUuid = (objUuid == null) ? null : objUuid.toString(); + if (currentItemUuid != null){ + //The Node already exists so we need to update the existing node + //rather than to replace it. + Node nodeToUpdate = collectionNode.getSession().getNodeByIdentifier(currentItemUuid); + objectConverter.update(session, currentItemUuid, item); + validUuidsForTheNode.add(currentItemUuid); + } + else{ + objectConverter.insert(session, collectionNode, elementJcrName, item); + validUuidsForTheNode.add(ReflectionUtils.getNestedProperty(item, uuidFieldName).toString()); + } + + } + else if (elementClassDescriptor.hasIdField()) { + + String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); + elementJcrName = ReflectionUtils.getNestedProperty(item, idFieldName).toString(); + + // Update existing JCR Nodes + if (collectionNode.hasNode(elementJcrName)) { + objectConverter.update(session, collectionNode, elementJcrName, item); + } + else { + // Add new collection elements + objectConverter.insert(session, collectionNode, elementJcrName, item); + } + + updatedItems.put(elementJcrName, item); + } + else { + elementJcrName = collectionDescriptor.getJcrElementName(); + if (elementJcrName == null) { // use PathFormat.checkFormat() here? + elementJcrName = COLLECTION_ELEMENT_NAME; + } + objectConverter.insert(session, collectionNode, elementJcrName, item); + } + } + + // Delete JCR nodes that are not present in the collection + if (elementClassDescriptor.hasUUIdField()) { + NodeIterator nodeIterator = collectionNode.getNodes(); + List removeNodes = new ArrayList(); + while (nodeIterator.hasNext()) { + Node currentNode = nodeIterator.nextNode(); + if (!validUuidsForTheNode.contains(currentNode.getIdentifier())) { + removeNodes.add(currentNode); + } + } + for (Node aNode : removeNodes){ + aNode.remove(); + } + return; + } + + // Delete JCR nodes that are not present in the collection + if (elementClassDescriptor.hasIdField()) { + NodeIterator nodeIterator = collectionNode.getNodes(); + List removeNodes = new ArrayList(); + while (nodeIterator.hasNext()) { + Node child = nodeIterator.nextNode(); + if (!updatedItems.containsKey(child.getName())) { + removeNodes.add(child); + } + } + for(int i = 0; i < removeNodes.size(); i++) { + ((Node) removeNodes.get(i)).remove(); + } + } + } + + + private void updateManagableMap(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects, String jcrName) + throws PathNotFoundException, RepositoryException, + VersionException, LockException, ConstraintViolationException, + ItemExistsException { + + + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); + Node collectionNode = parentNode.getNode(jcrName); + + Map map = (Map) objects.getObjects(); + Map updatedItems = new HashMap(); + for (Object key : map.keySet()) + { + Object item = map.get(key); + // Update existing JCR Nodes + if (collectionNode.hasNode(key.toString())) { + objectConverter.update(session, collectionNode, key.toString(), item); + } + else { + // Add new collection elements + objectConverter.insert(session, collectionNode, key.toString(), item); + } + updatedItems.put(key.toString(), item); + } + + // Delete the nodes that are not present in the Map + NodeIterator nodeIterator = collectionNode.getNodes(); + List removeNodes = new ArrayList(); + while (nodeIterator.hasNext()) { + Node child = nodeIterator.nextNode(); + if (!updatedItems.containsKey(child.getName())) { + removeNodes.add(child); + } + } + for(int i = 0; i < removeNodes.size(); i++) { + ((Node) removeNodes.get(i)).remove(); + } + + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + if (parentNode == null || !parentNode.hasNode(jcrName)) { + return null; + } + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + Node collectionNode = parentNode.getNode(jcrName); + NodeIterator children = collectionNode.getNodes(); + Class elementClass = ReflectionUtils.forName(collectionDescriptor.getElementClassName()); + + while (children.hasNext()) { + Node itemNode = children.nextNode(); + Object item = objectConverter.getObject(session, elementClass, itemNode.getPath()); + if ( objects instanceof ManageableCollection) + ((ManageableCollection)objects).addObject(item); + else + ((ManageableMap) objects).addObject(itemNode.getName(), item); + + } + + return objects; + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + if (parentNode == null || !parentNode.hasNode(jcrName)) { + return true; + } + return false; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/EnumCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/EnumCollectionConverterImpl.java new file mode 100644 index 00000000..03d02539 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/EnumCollectionConverterImpl.java @@ -0,0 +1,177 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.ValueFormatException; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.enumconverter.EnumTypeConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * Collection Mapping/convertion implementation used for enum collections + * + * This collection mapping strategy maps a collection into a JCR multi value property + * + * @author Christophe Lombart + * @author Alexandru Popescu + * @author Boni Gopalan + */ +public class EnumCollectionConverterImpl extends AbstractCollectionConverterImpl { + + private EnumTypeConverter enumConverter = new EnumTypeConverter(); + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public EnumCollectionConverterImpl( Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + try { + if (objects == null) { + return; + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + Value[] values = new Value[objects.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + Iterator collectionIterator = objects.getIterator(); + for (int i = 0; i < objects.getSize(); i++) { + Object fieldValue = collectionIterator.next(); + values[i] = enumConverter.getValue(valueFactory, fieldValue); + } + + parentNode.setProperty(jcrName, values); + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + // Delete existing values + if (parentNode.hasProperty(jcrName)) { + parentNode.setProperty(jcrName, (Value[]) null); + } + + if (objects == null) { + return; + } + + + // Add all collection element into an Value array + Value[] values = new Value[objects.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + int i = 0; + for (Iterator collectionIterator = objects.getIterator(); collectionIterator.hasNext(); i++) { + Object fieldValue = collectionIterator.next(); + values[i] = enumConverter.getValue(valueFactory, fieldValue); + } + + parentNode.setProperty(jcrName, values); + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + if (!parentNode.hasProperty(jcrName)) { + return null; + } + Property property = parentNode.getProperty(jcrName); + Value[] values = property.getValues(); + if (values == null || values.length <= 0){ + return null; + } + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + for (int i = 0; i < values.length; i++) { + ((ManageableCollection) objects).addObject(enumConverter.getObject(values[i])); + } + + return objects; + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), + vfe); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + if (!parentNode.hasProperty(jcrName)) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ManageableCollectionImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ManageableCollectionImpl.java new file mode 100644 index 00000000..b9c5b9ef --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ManageableCollectionImpl.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + +import java.util.Collection; +import java.util.Iterator; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; + +/** + * + * {@link ManageableCollection} ArrayList implementation + * + * @author Christophe Lombart + * + */ +public class ManageableCollectionImpl implements ManageableCollection +{ + + private Collection collection; + + public ManageableCollectionImpl(Collection collection) { + this.collection = collection; + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#addObject(java.lang.Object) + */ + public void addObject(Object object) + { + collection.add(object); + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#getIterator() + */ + public Iterator getIterator() + { + return collection.iterator(); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#getSize() + */ + public int getSize() + { + + return collection.size(); + } + + public Collection getObjects() { + + return collection; + } + + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ManageableMapImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ManageableMapImpl.java new file mode 100644 index 00000000..54cf0fcf --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ManageableMapImpl.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + +import java.util.Iterator; +import java.util.Map; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; + +/** + * + * {@link ManageableCollection} ArrayList implementation + * + * @author Christophe Lombart + * + */ +public class ManageableMapImpl implements ManageableMap +{ + + private Map map; + + + public ManageableMapImpl(Map map) { + super(); + this.map = map; + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#addObject(java.lang.Object) + */ + public void addObject(Object key, Object object) + { + map.put(key, object); + + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#getIterator() + */ + public Iterator getIterator() + { + return map.values().iterator(); + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#getSize() + */ + public int getSize() + { + + return map.size(); + } + + + public Map getObjects() { + + return map; + } + + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MapConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MapConverterImpl.java new file mode 100644 index 00000000..e41d0092 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MapConverterImpl.java @@ -0,0 +1,455 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.text.DecimalFormat; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.Property; +import javax.jcr.PropertyIterator; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.ValueFormatException; + +import org.apache.commons.lang.StringUtils; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * Collection Mapping/convertion implementation used for String collections + * + * This collection mapping strategy maps a collection into a JCR property + * + * @author Christophe Lombart + * @author Alexandru Popescu + * @author Boni Gopalan + */ +public class MapConverterImpl extends AbstractCollectionConverterImpl { + + + private static final DecimalFormat DF = new DecimalFormat("000000"); + + private static final String GRAVITY_TYPE = "gravity_type"; + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public MapConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + * + * ManageableObjects actually contains a Map + * + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + try { + if (objects == null) { + return; + } + + if( !(objects.getObjects() instanceof Map)){ + throw new ObjectContentManagerException("Input to MapConverterImpl not Map"); + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + + Node collectionNode; + if( !parentNode.hasNode(jcrName)){ + if (!StringUtils.isBlank(collectionDescriptor.getJcrType())) { + collectionNode = parentNode.addNode(jcrName, collectionDescriptor.getJcrType()); + } else { + collectionNode = parentNode.addNode(jcrName); + } + } else{ + collectionNode = parentNode.getNode(jcrName); + } + + Map valueMap = (Map) objects.getObjects(); + + for( String key : valueMap.keySet()){ + Object value = valueMap.get(key); + + if( value instanceof Boolean){ + Boolean booleanValue = (Boolean) value; + collectionNode.setProperty(key, booleanValue); + } else if( value instanceof Integer){ + Integer integerValue = (Integer) value; + collectionNode.setProperty(key, integerValue); + } else if( value instanceof Long){ + Long longValue = (Long) value; + collectionNode.setProperty(key, longValue); + } else if( value instanceof String){ + String stringValue = (String) value; + collectionNode.setProperty(key, stringValue); + } else if( value instanceof Date){ + Calendar dateValue = new GregorianCalendar( ); + dateValue.setTime((Date) value); + collectionNode.setProperty(key, dateValue); + } else if( value instanceof Map){ + persistMap( session , collectionNode, key, (Map) value); + } else if( value instanceof List){ + persistList( session , collectionNode, key, (List) value); + } else { + collectionNode.setProperty(key, value.toString()); + } + } + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + private void persistMap( Session session, Node parentNode, String jcrName, Map valueMap ) throws RepositoryException { + + try { + if (valueMap == null) { + return; + } + + Node collectionNode; + if( !parentNode.hasNode(jcrName)){ + collectionNode = parentNode.addNode(jcrName, parentNode.getPrimaryNodeType().getName()); + collectionNode.setProperty(GRAVITY_TYPE, "map"); + } else{ + collectionNode = parentNode.getNode(jcrName); + // remove nodes if they don't exist in supplied + NodeIterator nodes = collectionNode.getNodes(); + while(nodes.hasNext()){ + Node next = nodes.nextNode(); + if( !valueMap.containsKey(next.getName())){ + next.remove(); + } + } + } + + for( String key : valueMap.keySet()){ + Object value = valueMap.get(key); + + if( value instanceof Boolean){ + Boolean booleanValue = (Boolean) value; + collectionNode.setProperty(key, booleanValue); + } else if( value instanceof Integer){ + Integer integerValue = (Integer) value; + collectionNode.setProperty(key, integerValue); + } else if( value instanceof Long){ + Long longValue = (Long) value; + collectionNode.setProperty(key, longValue); + } else if( value instanceof String){ + String stringValue = (String) value; + collectionNode.setProperty(key, stringValue); + } else if( value instanceof Date){ + Calendar dateValue = new GregorianCalendar( ); + dateValue.setTime((Date) value); + collectionNode.setProperty(key, dateValue); + } else if( value instanceof Map){ + persistMap( session , collectionNode, key, (Map) value); + } else if( value instanceof List){ + persistList( session , collectionNode, key, (List) value); + } else { + collectionNode.setProperty(key, value.toString()); + } + } + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection", vfe); + } + } + + private void persistList( Session session, Node parentNode, String jcrName, List valueList ) throws RepositoryException { + + try { + if (valueList == null) { + return; + } + + Node collectionNode; + if( !parentNode.hasNode(jcrName)){ + collectionNode = parentNode.addNode(jcrName, parentNode.getPrimaryNodeType().getName()); + collectionNode.setProperty(GRAVITY_TYPE, "list"); + } else{ + collectionNode = parentNode.getNode(jcrName); + } + + int itemno = 0; + for( Object value : valueList){ + + String key = "item-" + DF.format(itemno); + itemno++; + + if( value instanceof Boolean){ + Boolean booleanValue = (Boolean) value; + collectionNode.setProperty(key, booleanValue); + } else if( value instanceof Integer){ + Integer integerValue = (Integer) value; + collectionNode.setProperty(key, integerValue); + } else if( value instanceof Long){ + Long longValue = (Long) value; + collectionNode.setProperty(key, longValue); + } else if( value instanceof String){ + String stringValue = (String) value; + collectionNode.setProperty(key, stringValue); + } else if( value instanceof Date){ + Calendar dateValue = new GregorianCalendar( ); + dateValue.setTime((Date) value); + collectionNode.setProperty(key, dateValue); + } else if( value instanceof Map){ + persistMap( session , collectionNode, key, (Map) value); + } else if( value instanceof List){ + persistList( session , collectionNode, key, (List) value); + } else { + collectionNode.setProperty(key, value.toString()); + } + } + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection", vfe); + } + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + * + * TODO: Delete properties that do not exist. + * + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + + doInsertCollection( session, parentNode, collectionDescriptor, objects); + + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + + String jcrName = getCollectionJcrName(collectionDescriptor); + + if( !parentNode.hasNode(jcrName)){ + return null; + } + + Node collectionNode = parentNode.getNode(jcrName); + + ManageableMap returnObjects = new ManageableMapImpl(new HashMap()); + + PropertyIterator properties = collectionNode.getProperties(); + while( properties.hasNext()){ + Property property = (Property) properties.next(); + if( !property.getName().startsWith("jcr:") && !property.getName().equals(GRAVITY_TYPE)){ + + switch (property.getValue().getType()){ + case PropertyType.BOOLEAN: + returnObjects.addObject(property.getName(),property.getBoolean()); + break; + case PropertyType.DECIMAL: + returnObjects.addObject(property.getName(),property.getDecimal()); + break; + case PropertyType.LONG: + returnObjects.addObject(property.getName(),property.getLong()); + break; + case PropertyType.STRING: + returnObjects.addObject(property.getName(),property.getString()); + break; + case PropertyType.DATE: + returnObjects.addObject(property.getName(),property.getDate().getTime()); + break; + } + } + } + + NodeIterator ni = collectionNode.getNodes(); + while( ni.hasNext()){ + Node subnode = ni.nextNode(); + String type = gravityNodeType(subnode); + Object obj; + if(type.equals("list")){ + obj = getList(session, subnode); + } else { + obj = getMap(session, subnode); + } + + returnObjects.addObject(subnode.getName(), obj); + } + + return returnObjects; + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), + vfe); + } + } + + private Map getMap( Session session, Node node) throws RepositoryException{ + + Map returnObjects = new HashMap(); + + PropertyIterator properties = node.getProperties(); + while( properties.hasNext()){ + Property property = (Property) properties.next(); + if( !property.getName().startsWith("jcr:") && !property.getName().equals(GRAVITY_TYPE) ){ + + switch (property.getValue().getType()){ + case PropertyType.BOOLEAN: + returnObjects.put(property.getName(),property.getBoolean()); + break; + case PropertyType.DECIMAL: + returnObjects.put(property.getName(),property.getDecimal()); + break; + case PropertyType.LONG: + returnObjects.put(property.getName(),property.getLong()); + break; + case PropertyType.STRING: + returnObjects.put(property.getName(),property.getString()); + break; + case PropertyType.DATE: + returnObjects.put(property.getName(),property.getDate().getTime()); + break; + } + } + } + + NodeIterator ni = node.getNodes(); + while( ni.hasNext()){ + Node subnode = ni.nextNode(); + + String type = gravityNodeType(subnode); + Object obj; + if(type.equals("list")){ + obj = getList(session, subnode); + } else { + obj = getMap(session, subnode); + } + + returnObjects.put(subnode.getName(), obj); + } + + return returnObjects; + } + + + private Collection getList( Session session, Node node) throws RepositoryException{ + + Map returnObjects = new TreeMap(); + + PropertyIterator properties = node.getProperties(); + while( properties.hasNext()){ + Property property = (Property) properties.next(); + if( !property.getName().startsWith("jcr:") && !property.getName().equals(GRAVITY_TYPE)){ + + switch (property.getValue().getType()){ + case PropertyType.BOOLEAN: + returnObjects.put(property.getName(),property.getBoolean()); + break; + case PropertyType.DECIMAL: + returnObjects.put(property.getName(),property.getDecimal()); + break; + case PropertyType.LONG: + returnObjects.put(property.getName(),property.getLong()); + break; + case PropertyType.STRING: + returnObjects.put(property.getName(),property.getString()); + break; + case PropertyType.DATE: + returnObjects.put(property.getName(),property.getDate().getTime()); + break; + } + } + } + + NodeIterator ni = node.getNodes(); + while( ni.hasNext()){ + Node subnode = ni.nextNode(); + + String type = gravityNodeType(subnode); + Object obj; + if(type.equals("list")){ + obj = getList(session, subnode); + } else { + obj = getMap(session, subnode); + } + + returnObjects.put(subnode.getName(), obj); + + } + + return returnObjects.values(); + } + + private String gravityNodeType( Node node ) throws RepositoryException{ + if(node.hasProperty(GRAVITY_TYPE)){ + return node.getProperty(GRAVITY_TYPE).getString(); + } + return "map"; + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + + return parentNode.getProperties().getSize()>0; + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MapReferenceValueEncoder.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MapReferenceValueEncoder.java new file mode 100644 index 00000000..a6372dcb --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MapReferenceValueEncoder.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +public class MapReferenceValueEncoder { + + private final static String PREFIX="OCM:"; + final static String KEY_TOKEN="MAPKEY:"; + final static String REFERENCE_TOKEN="MAPVALUE:"; + + public static String decodeKey(String encoded) + { + String[] splitted = encoded.split(PREFIX); + return splitted[1].replaceAll(KEY_TOKEN, ""); + } + + public static String decodeReference(String encoded) + { + String[] splitted = encoded.split(PREFIX); + return splitted[2].replaceAll(REFERENCE_TOKEN, ""); + } + + public static String encodeKeyAndReference(String key, String reference) + { + return PREFIX+KEY_TOKEN+key+PREFIX+REFERENCE_TOKEN+reference; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MultiValueCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MultiValueCollectionConverterImpl.java new file mode 100644 index 00000000..bea6588c --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/MultiValueCollectionConverterImpl.java @@ -0,0 +1,213 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.ValueFormatException; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.UndefinedTypeConverterImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; + +/** + * Collection Mapping/convertion implementation used for multi values properties + * + * This collection mapping strategy maps a collection into a JCR multi value property + * + * @author Christophe Lombart + * @author Alexandru Popescu + * @author Boni Gopalan + */ +public class MultiValueCollectionConverterImpl extends AbstractCollectionConverterImpl { + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public MultiValueCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + try { + if (objects == null) { + return; + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + Value[] values = new Value[objects.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + Iterator collectionIterator = objects.getIterator(); + for (int i = 0; i < objects.getSize(); i++) { + Object fieldValue = collectionIterator.next(); + AtomicTypeConverter atomicTypeConverter = (AtomicTypeConverter) atomicTypeConverters + .get(fieldValue.getClass()); + //If there is no proper conversion strategy defined for a specific bean type + //then system will make a best effort conversion strategy using UndefinedTypeConverter. + //@author:Boni Gopalan + if (atomicTypeConverter == null){ + atomicTypeConverter = new UndefinedTypeConverterImpl(); + } + values[i] = atomicTypeConverter.getValue(valueFactory, fieldValue); + } + + parentNode.setProperty(jcrName, values); + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + // Delete existing values + if (parentNode.hasProperty(jcrName)) { + parentNode.setProperty(jcrName, (Value[]) null); + } + + if (objects == null) { + return; + } + + + // Add all collection element into an Value array + Value[] values = new Value[objects.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + int i = 0; + for (Iterator collectionIterator = objects.getIterator(); collectionIterator.hasNext(); i++) { + Object fieldValue = collectionIterator.next(); + AtomicTypeConverter atomicTypeConverter = (AtomicTypeConverter) atomicTypeConverters + .get(fieldValue.getClass()); + //If there is no proper conversion strategy defined for a specific bean type + //then system will make a best effort conversion strategy using UndefinedTypeConverter. + //@author:Boni Gopalan + if (atomicTypeConverter == null){ + atomicTypeConverter = new UndefinedTypeConverterImpl(); + } + + values[i] = atomicTypeConverter.getValue(valueFactory, fieldValue); + } + + parentNode.setProperty(jcrName, values); + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + if (!parentNode.hasProperty(jcrName)) { + return null; + } + Property property = parentNode.getProperty(jcrName); + Value[] values = property.getValues(); + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + String elementClassName = collectionDescriptor.getElementClassName(); + Class elementClass = ReflectionUtils.forName(elementClassName); + // For multi value collections, only Collections are supported + if (! (objects instanceof ManageableCollection)) + { + + throw new JcrMappingException("Impossible to retrieve the attribute " + + collectionDescriptor.getFieldName() + " in the class " + + collectionDescriptor.getClassDescriptor().getClassName() + + " because it is not a collection"); + } + + for (int i = 0; i < values.length; i++) { + AtomicTypeConverter atomicTypeConverter = (AtomicTypeConverter) atomicTypeConverters + .get(elementClass); + //If there is no proper conversion strategy defined for a specific bean type + //then system will make a best effort conversion strategy using UndefinedTypeConverter. + //@author:Boni Gopalan + if (atomicTypeConverter == null){ + atomicTypeConverter = new UndefinedTypeConverterImpl(); + } + ((ManageableCollection) objects).addObject(atomicTypeConverter.getObject(values[i])); + } + + return objects; + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), + vfe); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + if (!parentNode.hasProperty(jcrName)) { + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/NTCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/NTCollectionConverterImpl.java new file mode 100755 index 00000000..516439b1 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/NTCollectionConverterImpl.java @@ -0,0 +1,318 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.ValueFormatException; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.query.InvalidQueryException; +import javax.jcr.query.Query; +import javax.jcr.query.QueryResult; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Collection Mapping/convertion based on node type. + * + * This collection mapping strategy maps the collection elements into subnodes based on the same node types. + * + * There are 3 constraints in this collection converter : + * 1/ this is not possible to have 2 different collections in the main object which are used the same jcr node type for their elements. + * 2/ this is not possible to make a distinction between an empty collection and an null collection. + * 3/ Map are not supported. + * + * + * If the collection element class contains an id (see the FieldDescriptor definition), this id value is used to build the collection element node name. + * Otherwise, the element node name is a simple constant (collection-element) + * + * Example - without an id attribute: + * /test (Main object containing the collection field ) + * /collection-element (node used to store the first collection element) + * /item-prop + * .... + * /collection-element (node used to store the second collection element) + * ... + * + * Each "collection-element" nodes have the same jcr node type + * + * Example - with an id attribute: + * /test (Main object containing the collection field ) + * /aValue (id value assigned to the first element) + * /item-prop + * .... + * /anotherValue (id value assigned to the first element) + * ... + * + * Each collection element nodes have the same jcr node type + * + * @author Christophe Lombart + * + */ +public class NTCollectionConverterImpl extends AbstractCollectionConverterImpl { + + private final static Logger log = LoggerFactory.getLogger(NTCollectionConverterImpl.class); + + protected static final String COLLECTION_ELEMENT_NAME = "collection-element"; + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public NTCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) { + if (objects == null) { + return; + } + + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); + + Iterator collectionIterator = objects.getIterator(); + while (collectionIterator.hasNext()) { + Object item = collectionIterator.next(); + String elementJcrName = null; + + // If the element object has a unique id => the element jcr node name = the id value + if (elementClassDescriptor.hasIdField()) { + String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); + elementJcrName = ReflectionUtils.getNestedProperty(item, idFieldName).toString(); + } + else { + elementJcrName = collectionDescriptor.getJcrElementName(); + if (elementJcrName == null) { // use PathFormat.checkFormat() here? + elementJcrName = COLLECTION_ELEMENT_NAME; + } + } + + objectConverter.insert(session, parentNode, elementJcrName, item); + } + } + + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass( + ReflectionUtils.forName(collectionDescriptor.getElementClassName())); + + if (objects == null || !elementClassDescriptor.hasIdField()) { + this.deleteCollectionItems(session, + parentNode, + elementClassDescriptor.getJcrType()); + } + + if (objects == null) { + return; + } + + Iterator collectionIterator = objects.getIterator(); + Map updatedItems = new HashMap(); + while (collectionIterator.hasNext()) { + Object item = collectionIterator.next(); + + String elementJcrName = null; + + if (elementClassDescriptor.hasIdField()) { + String idFieldName = elementClassDescriptor.getIdFieldDescriptor().getFieldName(); + elementJcrName = ReflectionUtils.getNestedProperty(item, idFieldName).toString(); + + // Update existing JCR Nodes + if (parentNode.hasNode(elementJcrName)) { + objectConverter.update(session, parentNode, elementJcrName, item); + } + else { + // Add new collection elements + objectConverter.insert(session, parentNode, elementJcrName, item); + } + + updatedItems.put(elementJcrName, item); + } + else { + elementJcrName = collectionDescriptor.getJcrElementName(); + if (elementJcrName == null) { // use PathFormat.checkFormat() here? + elementJcrName = COLLECTION_ELEMENT_NAME; + } + objectConverter.insert(session, parentNode, elementJcrName, item); + } + } + + // Delete JCR nodes that are not present in the collection + NodeIterator nodes = this.getCollectionNodes(session, parentNode, + elementClassDescriptor.getJcrType()); + if (nodes != null && elementClassDescriptor.hasIdField()) { + + + while (nodes.hasNext()) { + Node child = (Node) nodes.next(); + + if (!updatedItems.containsKey(child.getName())) { + child.remove(); + } + } + } + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter#getCollection(javax.jcr.Session, javax.jcr.Node, org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, java.lang.Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass( ReflectionUtils.forName(collectionDescriptor.getElementClassName())); + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + + NodeIterator nodes = this.getCollectionNodes(session, parentNode, elementClassDescriptor.getJcrType()); + + if (nodes == null || nodes.getSize() == 0) + { + return null; + } + + while (nodes.hasNext()) { + Node itemNode = (Node) nodes.next(); + if (log.isDebugEnabled()) { + log.debug("Collection node found: {}", itemNode.getPath()); + } + Object item = objectConverter.getObject(session, itemNode.getPath()); + mapper.getClassDescriptorByClass(item.getClass()); + if ( objects instanceof ManageableCollection) + ((ManageableCollection)objects).addObject(item); + else { + if (!elementClassDescriptor.hasIdField()) + { + throw new JcrMappingException("Impossible to use a map for the field : " + + collectionDescriptor.getFieldName() + + "in the class : " + collectionDescriptor.getCollectionClassName() + + ". The element objects have no id field (check their OCM mapping)"); + } + Object elementId = ReflectionUtils.getNestedProperty(item, + elementClassDescriptor.getIdFieldDescriptor().getFieldName()); + ((ManageableMap) objects).addObject(elementId, item); + } + + } + + return objects; + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + * + * return true If the parent node doesn't contains node based on the node type associated to the collection elements + * + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + + String elementClassName = collectionDescriptor.getElementClassName(); + ClassDescriptor elementClassDescriptor = mapper.getClassDescriptorByClass(ReflectionUtils.forName(elementClassName)); + QueryResult queryResult = getQuery(session, parentNode, elementClassDescriptor.getJcrType()); + return queryResult.getNodes().getSize() == 0; + } + + private NodeIterator getCollectionNodes(Session session, Node parentNode, String itemNodeType) + throws PathNotFoundException, ValueFormatException, RepositoryException { + + List collectionNodes = null; + + QueryResult queryResult = getQuery(session, parentNode, itemNodeType); + return queryResult.getNodes(); + + } + + private void deleteCollectionItems(Session session, Node parentNode, String itemNodeType) + throws VersionException, + LockException, + ConstraintViolationException, + PathNotFoundException, + ValueFormatException, + RepositoryException + { + NodeIterator nodes = this.getCollectionNodes(session, parentNode, itemNodeType); + if (nodes == null || nodes.getSize()==0) return; + + while (nodes.hasNext()) { + Node node = (Node) nodes.next(); + node.remove(); + } + } + + + + private QueryResult getQuery(Session session, Node parentNode, String jcrNodeType) throws RepositoryException, InvalidQueryException { + String jcrExpression= ""; + if (!parentNode.getPath().startsWith("/jcr:system/jcr:versionStorage")) + { + jcrExpression = "SELECT * FROM " + jcrNodeType + " WHERE jcr:path LIKE '" + parentNode.getPath() + + "/%' AND NOT jcr:path LIKE '" + parentNode.getPath() + "/%/%'"; + //FIXME: for doIsNull(..) only need to know if there are attributes or childnodes, queryResult.getNodes().getSize() delivers -1 + jcrExpression += " order by jcr:path"; + } + else + { + + jcrExpression = "SELECT * FROM nt:frozenNode" + " WHERE jcr:path LIKE '" + parentNode.getPath() + "/%'" + + " AND NOT jcr:path LIKE '" + parentNode.getPath() + "/%/%'" + + " AND jcr:frozenPrimaryType = '" + jcrNodeType + "'"; + + + } + @SuppressWarnings("deprecation") + Query jcrQuery = session.getWorkspace().getQueryManager().createQuery(jcrExpression, javax.jcr.query.Query.SQL); + QueryResult queryResult = jcrQuery.execute(); + return queryResult; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ReferenceCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ReferenceCollectionConverterImpl.java new file mode 100644 index 00000000..a98f2701 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ReferenceCollectionConverterImpl.java @@ -0,0 +1,178 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.ValueFormatException; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * + * This collection mapping strategy maps a collection of String into a JCR multi value property based on the reference type + * + * @author Christophe Lombart + */ +public class ReferenceCollectionConverterImpl extends AbstractCollectionConverterImpl { + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public ReferenceCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + addUuidProperties(session, parentNode, collectionDescriptor, objects); + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + // Delete existing values + if (parentNode.hasProperty(jcrName)) { + parentNode.setProperty(jcrName, (Value[]) null); + } + + if (objects == null) { + return; + } + + + addUuidProperties(session, parentNode, collectionDescriptor, objects); + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + if (!parentNode.hasProperty(jcrName)) { + return null; + } + Property property = parentNode.getProperty(jcrName); + Value[] values = property.getValues(); + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + for (int i = 0; i < values.length; i++) { + + if (objects instanceof ManageableCollection) + ((ManageableCollection)objects).addObject(values[i].getString()); + else + throw new ObjectContentManagerException( + "Unsupported data type in ReferenceCollectionConverter : " + objects.getClass().getName()); + } + + return objects; + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), + vfe); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + + if (!parentNode.hasProperty(jcrName)) { + return true; + } + return false; + } + + private void addUuidProperties(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, ManageableObjects objects) + throws UnsupportedRepositoryOperationException, RepositoryException, VersionException, LockException, ConstraintViolationException { + try { + if (objects == null) { + return; + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + Value[] values = new Value[objects.getSize()]; + ValueFactory valueFactory = session.getValueFactory(); + Iterator collectionIterator = objects.getIterator(); + for (int i = 0; i < objects.getSize(); i++) { + String uuid = (String) collectionIterator.next(); + values[i] = valueFactory.createValue(uuid, PropertyType.REFERENCE); + + } + + parentNode.setProperty(jcrName, values); + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ResidualNodesCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ResidualNodesCollectionConverterImpl.java new file mode 100644 index 00000000..1add0412 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ResidualNodesCollectionConverterImpl.java @@ -0,0 +1,189 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.ValueFormatException; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * The ResidualNodesCollectionConverterImpl is a collection + * converter for multiple child nodes accessed through Node.getNodes(String + * pattern). + * + * @author Felix Meschberger + */ +public class ResidualNodesCollectionConverterImpl extends + AbstractCollectionConverterImpl { + + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public ResidualNodesCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doInsertCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) { + + if (!(objects instanceof ManageableMap)) { + return; + } + + Map map = (Map) objects.getObjects(); + for (Iterator ei=map.entrySet().iterator(); ei.hasNext(); ) { + Map.Entry entry = (Map.Entry) ei.next(); + String name = String.valueOf(entry.getKey()); + objectConverter.insert(session, parentNode, name, entry.getValue()); + } + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doUpdateCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + String jcrName = getCollectionJcrName(collectionDescriptor); + if (!(objects instanceof ManageableMap)) { + for (NodeIterator ni=parentNode.getNodes(jcrName); ni.hasNext(); ) { + ni.nextNode().remove(); + } + return; + } + + Map map = (Map) objects.getObjects(); + Set updatedItems = new HashSet(); + for (Iterator ei=map.entrySet().iterator(); ei.hasNext(); ) { + Map.Entry entry = (Map.Entry) ei.next(); + String elementJcrName = String.valueOf(entry.getKey()); + Object item = entry.getValue(); + + // Update existing JCR Nodes + if (parentNode.hasNode(elementJcrName)) { + objectConverter.update(session, parentNode, elementJcrName, item); + } + else { + // Add new collection elements + objectConverter.insert(session, parentNode, elementJcrName, item); + } + + updatedItems.add(elementJcrName); + } + + // Delete JCR nodes that are not present in the collection + NodeIterator nodeIterator = parentNode.getNodes(jcrName); + List removeNodes = new ArrayList(); + while (nodeIterator.hasNext()) { + Node child = nodeIterator.nextNode(); + if (!updatedItems.contains(child.getName())) { + removeNodes.add(child); + } + } + for(int i = 0; i < removeNodes.size(); i++) { + ((Node) removeNodes.get(i)).remove(); + } + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + NodeIterator ni = parentNode.getNodes(jcrName); + if (!ni.hasNext()) { + return null; + } + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + while (ni.hasNext()) { + Node node = ni.nextNode(); + + // ignore protected nodes here + if (node.getDefinition().isProtected()) { + continue; + } + + Object item = objectConverter.getObject(session, node.getPath()); + if (objects instanceof Map) { + String name = node.getName(); + ((Map) objects).put(name, item); + } + else { + if (objects instanceof ManageableCollection) + ((ManageableCollection)objects).addObject(item); + else + { + String name = node.getName(); + ((ManageableMap)objects).addObject(name, item); + } + } + } + return objects; + + } catch (ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + "for class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) + throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + return (parentNode == null || !parentNode.getNodes(jcrName).hasNext()); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ResidualPropertiesCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ResidualPropertiesCollectionConverterImpl.java new file mode 100644 index 00000000..9f308846 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/ResidualPropertiesCollectionConverterImpl.java @@ -0,0 +1,245 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.PropertyIterator; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.ValueFormatException; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; + +/** + * The ResidualPropertiesCollectionConverterImpl is a collection + * converter for multiple properties accessed through + * Node.getProperties(String pattern). + * + * @author Felix Meschberger + */ +public class ResidualPropertiesCollectionConverterImpl extends + AbstractCollectionConverterImpl { + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public ResidualPropertiesCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doInsertCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + internalSetProperties(session, parentNode, collectionDescriptor, + objects, false); + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + */ + protected void doUpdateCollection(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + internalSetProperties(session, parentNode, collectionDescriptor, + objects, true); + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + String jcrName = getCollectionJcrName(collectionDescriptor); + PropertyIterator pi = parentNode.getProperties(jcrName); + if (!pi.hasNext()) { + return null; + } + + ManageableObjects objects = ManageableObjectsUtil.getManageableObjects(collectionFieldClass); + AtomicTypeConverter atomicTypeConverter = getAtomicTypeConverter(collectionDescriptor); + + while (pi.hasNext()) { + Property prop = pi.nextProperty(); + + // ignore protected properties here + if (prop.getDefinition().isProtected()) { + continue; + } + + // handle multvalues as a list + Object value; + if (prop.getDefinition().isMultiple()) { + List valueList = new ArrayList(); + Value[] values = prop.getValues(); + for (int i = 0; i < values.length; i++) { + valueList.add(atomicTypeConverter.getObject(values[i])); + } + value = valueList; + } else { + value = atomicTypeConverter.getObject(prop.getValue()); + } + + if (objects instanceof Map) { + String name = prop.getName(); + ((Map) objects).put(name, value); + } else { + if (objects instanceof ManageableCollection) + ((ManageableCollection)objects).addObject(value); + else + { + String name = prop.getName(); + ((ManageableMap)objects).addObject(name, value); + } + } + } + + return objects; + } catch (ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + "for class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) + throws RepositoryException { + String jcrName = getCollectionJcrName(collectionDescriptor); + return (parentNode == null || !parentNode.getProperties(jcrName).hasNext()); + } + + private void internalSetProperties(Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects, boolean removeExisting) + throws RepositoryException { + + String jcrName = getCollectionJcrName(collectionDescriptor); + + // can only persist maps, not general collections + if (!(objects instanceof ManageableMap)) { + return; + } + + // Delete existing values - before checking for collection ! + if (removeExisting) { + for (PropertyIterator pi = parentNode.getProperties(jcrName); pi.hasNext();) { + Property prop = pi.nextProperty(); + if (!prop.getDefinition().isProtected()) { + prop.remove(); + } + } + } + + AtomicTypeConverter atomicTypeConverter = getAtomicTypeConverter(collectionDescriptor); + + try { + Map map = (Map) objects.getObjects(); + ValueFactory valueFactory = session.getValueFactory(); + for (Iterator ei = map.entrySet().iterator(); ei.hasNext();) { + Map.Entry entry = (Map.Entry) ei.next(); + String name = String.valueOf(entry.getKey()); + + // verify the property is not an existing protected property + if (parentNode.hasProperty(name) + && parentNode.getProperty(name).getDefinition().isProtected()) { + continue; + } + + Object value = entry.getValue(); + if (value instanceof List) { + // multi value + List valueList = (List) value; + Value[] jcrValues = new Value[valueList.size()]; + int i = 0; + for (Iterator vi = valueList.iterator(); vi.hasNext();) { + value = vi.next(); + jcrValues[i++] = atomicTypeConverter.getValue( + valueFactory, value); + } + parentNode.setProperty(name, jcrValues); + } else { + // single value + Value jcrValue = atomicTypeConverter.getValue(valueFactory, + value); + parentNode.setProperty(name, jcrValue); + } + } + } catch (ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + /** + * Returns the AtomicTypeConverter for the element class of the described + * collection. If no such converter can be found a ObjectContentManagerException + * is thrown. + * + * @param collectionDescriptor The descriptor of the collection for whose + * elements an AtomicTypeConverter is requested. + * + * @return The AtomicTypeConverter for the elements of the collection + * + * @throws ObjectContentManagerException if no such type converter is registered + */ + private AtomicTypeConverter getAtomicTypeConverter(CollectionDescriptor collectionDescriptor) { + String elementClassName = collectionDescriptor.getElementClassName(); + Class elementClass = ReflectionUtils.forName(elementClassName); + AtomicTypeConverter atc = (AtomicTypeConverter) atomicTypeConverters.get(elementClass); + if (atc != null) { + return atc; + } + + throw new ObjectContentManagerException( + "Cannot get AtomicTypeConverter for element class " + + elementClassName + " of class " + + collectionDescriptor.getClassDescriptor().getClassName()); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/StringCollectionConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/StringCollectionConverterImpl.java new file mode 100644 index 00000000..f328dc69 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/collectionconverter/impl/StringCollectionConverterImpl.java @@ -0,0 +1,215 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter.impl; + + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.Property; +import javax.jcr.PropertyIterator; +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.ValueFormatException; + +import org.apache.commons.lang.StringUtils; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +/** + * Collection Mapping/convertion implementation used for String collections + * + * This collection mapping strategy maps a collection into a JCR property + * + * @author Christophe Lombart + * @author Alexandru Popescu + * @author Boni Gopalan + */ +public class StringCollectionConverterImpl extends AbstractCollectionConverterImpl { + + /** + * Constructor + * + * @param atomicTypeConverters + * @param objectConverter + * @param mapper + */ + public StringCollectionConverterImpl(Map atomicTypeConverters, + ObjectConverter objectConverter, + Mapper mapper) { + super(atomicTypeConverters, objectConverter, mapper); + } + + /** + * + * @see AbstractCollectionConverterImpl#doInsertCollection(Session, Node, CollectionDescriptor, ManageableCollection) + * + * ManageableObjects actually contains a Map + * + */ + protected void doInsertCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + try { + if (objects == null) { + return; + } + + if( !(objects.getObjects() instanceof Map)){ + throw new ObjectContentManagerException("Input to StringCollectionConverter not Map"); + } + + String jcrName = getCollectionJcrName(collectionDescriptor); + + Node collectionNode; + if( !parentNode.hasNode(jcrName)){ + if (!StringUtils.isBlank(collectionDescriptor.getJcrType())) { + collectionNode = parentNode.addNode(jcrName, collectionDescriptor.getJcrType()); + } else { + collectionNode = parentNode.addNode(jcrName); + } + } else{ + collectionNode = parentNode.getNode(jcrName); + } + + Map valueMap = (Map) objects.getObjects(); + + for( String key : valueMap.keySet()){ + Object value = valueMap.get(key); + + if( value instanceof Boolean){ + Boolean booleanValue = (Boolean) value; + collectionNode.setProperty(key, booleanValue); + } else if( value instanceof Integer){ + Integer integerValue = (Integer) value; + collectionNode.setProperty(key, integerValue); + } else if( value instanceof Long){ + Long longValue = (Long) value; + collectionNode.setProperty(key, longValue); + } else if( value instanceof String){ + String stringValue = (String) value; + collectionNode.setProperty(key, stringValue); + } else if( value instanceof Date){ + Calendar dateValue = new GregorianCalendar( ); + dateValue.setTime((Date) value); + collectionNode.setProperty(key, dateValue); + } else { + collectionNode.setProperty(key, value.toString()); + } + } + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot insert collection field : " + + collectionDescriptor.getFieldName() + + " of class " + + collectionDescriptor.getClassDescriptor().getClassName(), vfe); + } + } + + /** + * + * @see AbstractCollectionConverterImpl#doUpdateCollection(Session, Node, CollectionDescriptor, ManageableCollection) + * + * TODO: Delete properties that do not exist. + * + */ + protected void doUpdateCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + ManageableObjects objects) throws RepositoryException { + + + doInsertCollection( session, parentNode, collectionDescriptor, objects); + + } + + /** + * @see AbstractCollectionConverterImpl#doGetCollection(Session, Node, CollectionDescriptor, Class) + */ + protected ManageableObjects doGetCollection(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + try { + + String jcrName = getCollectionJcrName(collectionDescriptor); + + if( !parentNode.hasNode(jcrName)){ + return null; + } + + Node collectionNode = parentNode.getNode(jcrName); + + ManageableMap returnObjects = new ManageableMapImpl(new HashMap()); + PropertyIterator properties = collectionNode.getProperties(); + while( properties.hasNext()){ + Property property = (Property) properties.next(); + if( !property.getName().startsWith("jcr:")){ + + switch (property.getValue().getType()){ + case PropertyType.BOOLEAN: + returnObjects.addObject(property.getName(),property.getBoolean()); + break; + case PropertyType.DECIMAL: + returnObjects.addObject(property.getName(),property.getDecimal()); + break; + case PropertyType.LONG: + returnObjects.addObject(property.getName(),property.getLong()); + break; + case PropertyType.STRING: + returnObjects.addObject(property.getName(),property.getString()); + break; + case PropertyType.DATE: + returnObjects.addObject(property.getName(),property.getDate().getTime()); + break; + } + } + } + + return returnObjects; + } + catch(ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot get the collection field : " + + collectionDescriptor.getFieldName() + + "for class " + collectionDescriptor.getClassDescriptor().getClassName(), + vfe); + } + } + + /** + * @see AbstractCollectionConverterImpl#doIsNull(Session, Node, CollectionDescriptor, Class) + */ + protected boolean doIsNull(Session session, + Node parentNode, + CollectionDescriptor collectionDescriptor, + Class collectionFieldClass) throws RepositoryException { + + return parentNode.getProperties().getSize()>0; + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/enumconverter/EnumTypeConverter.java b/src/main/java/org/apache/jackrabbit/ocm/manager/enumconverter/EnumTypeConverter.java new file mode 100644 index 00000000..ede28827 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/enumconverter/EnumTypeConverter.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.enumconverter; + +import java.io.InvalidClassException; + +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.commons.lang.StringUtils; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + + +/** +* +* SimpleEnumerationTypeConverter class. +* +* This converter can map type Enum (java.lang.Enum) to JCR properties and back. +* +* @author Boni Gopalan +*/ +public class EnumTypeConverter implements AtomicTypeConverter { + + public Object getObject(Value value) { + try { + String propertyValue = value.getString(); + String[] enumerationDef = StringUtils.split(propertyValue, ':'); + String enumerationClass = enumerationDef[0]; + String enumerationValue = enumerationDef[1]; + Enum[] enumerations = (Enum[]) Class.forName(enumerationClass) + .getEnumConstants(); + int size = enumerations.length; + + for (int i = 0; i < size; i++) { + if (enumerations[i].name().equals(enumerationValue)) { + return enumerations[i]; + } + } + + throw new RuntimeException(new InvalidClassException(enumerationClass + + " Does not contain an enumeration " + enumerationValue)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public Value getValue(ValueFactory valueFactory, Object object) { + if (object == null) { + return null; + } + + if (!(object instanceof Enum)) { + throw new RuntimeException(new InvalidClassException(EnumTypeConverter.class.getSimpleName() + + " Can only convert simple Enumerations")); + } + + String value; + Enum anEnum = (Enum) (object); + value = anEnum.getDeclaringClass().getName() + ":" + anEnum.name(); + + return valueFactory.createValue(value); + } + + public String getXPathQueryValue(ValueFactory valueFactory, Object object) { + Value value = getValue(valueFactory, object); + + try { + return "'" + value.getString() + "'"; + } catch (Exception e) { + throw new RuntimeException(e.fillInStackTrace()); + } + } +} diff --git a/src/java/org/apache/portals/graffito/jcr/persistence/impl/CustomNodeTypeCreatorImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/CustomNodeTypeCreatorImpl.java similarity index 57% rename from src/java/org/apache/portals/graffito/jcr/persistence/impl/CustomNodeTypeCreatorImpl.java rename to src/main/java/org/apache/jackrabbit/ocm/manager/impl/CustomNodeTypeCreatorImpl.java index ae6e8885..4e1cb579 100644 --- a/src/java/org/apache/portals/graffito/jcr/persistence/impl/CustomNodeTypeCreatorImpl.java +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/CustomNodeTypeCreatorImpl.java @@ -1,26 +1,26 @@ /* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +package org.apache.jackrabbit.ocm.manager.impl; -import org.apache.portals.graffito.jcr.exception.CustomNodeTypeCreationException; -import org.apache.portals.graffito.jcr.persistence.CustomNodeTypeCreator; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; +import org.apache.jackrabbit.ocm.exception.CustomNodeTypeCreationException; +import org.apache.jackrabbit.ocm.manager.CustomNodeTypeCreator; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Default implementation of the jackrabbit custom node creator. * @@ -28,69 +28,69 @@ * @version $Id: Exp $ */ public class CustomNodeTypeCreatorImpl implements CustomNodeTypeCreator { - + /** Logger. */ - private final static Log log = LogFactory.getLog(CustomNodeTypeCreatorImpl.class); - + private final static Logger log = LoggerFactory.getLogger(CustomNodeTypeCreatorImpl.class); + /** Session to the jcr repository. */ - private PersistenceManagerImpl jcrSession; - + private ObjectContentManagerImpl jcrSession; + /** Creates a new instance of CustomNodeTypeCreatorImpl. */ public CustomNodeTypeCreatorImpl() { } - - /** Creates a new instance of CustomNodeTypeCreatorImpl with a jcr session. + + /** Creates a new instance of CustomNodeTypeCreatorImpl with a jcr session. * @param jcrSession JcrSession */ - public CustomNodeTypeCreatorImpl(PersistenceManagerImpl jcrSession) + public CustomNodeTypeCreatorImpl(ObjectContentManagerImpl jcrSession) { this.jcrSession = jcrSession; } /** This method is supposed to create custom node types on repository * setup. - * - * @throws org.apache.portals.graffito.jcr.exception.CustomNodeTypeCreationException + * + * @throws org.apache.jackrabbit.ocm.exception.CustomNodeTypeCreationException * @return true/false */ public boolean createInitialJcrCustomNodeTypes() throws CustomNodeTypeCreationException { - + // TODO - + return true; } /** Method to add a jcr custom node type to an existing jcr repository. - * - * @throws org.apache.portals.graffito.jcr.exception.CustomNodeTypeCreationException + * + * @throws org.apache.jackrabbit.ocm.exception.CustomNodeTypeCreationException * @return true/false */ public boolean addJcrCustomNodeType() throws CustomNodeTypeCreationException { - + // TODO - + return false; } - + /** Setter for property jcrSession. - * + * * @param jcrSession JcrSession */ - public void setJcrSession(PersistenceManagerImpl jcrSession) + public void setJcrSession(ObjectContentManagerImpl jcrSession) { this.jcrSession = jcrSession; } /** Getter for property jcrSession. - * + * * @return jcrSession */ - public PersistenceManager getJcrSession() + public ObjectContentManager getJcrSession() { return jcrSession; } diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectContentManagerImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectContentManagerImpl.java new file mode 100644 index 00000000..92576250 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectContentManagerImpl.java @@ -0,0 +1,1189 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.impl; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.jcr.InvalidItemStateException; +import javax.jcr.Item; +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.Property; +import javax.jcr.PropertyIterator; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import javax.jcr.lock.LockException; +import javax.jcr.lock.LockManager; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.nodetype.NodeType; +import javax.jcr.nodetype.PropertyDefinition; +import javax.jcr.query.InvalidQueryException; +import javax.jcr.query.QueryResult; +import javax.jcr.version.VersionHistory; +import javax.jcr.version.VersionManager; + +import org.apache.commons.lang.StringUtils; +import org.apache.jackrabbit.ocm.exception.IllegalUnlockException; +import org.apache.jackrabbit.ocm.exception.IncorrectPersistentClassException; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.LockedException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.VersionException; +import org.apache.jackrabbit.ocm.lock.Lock; +import org.apache.jackrabbit.ocm.manager.ManagerConstant; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.DefaultAtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.cache.ObjectCache; +import org.apache.jackrabbit.ocm.manager.cache.impl.RequestObjectCacheImpl; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.impl.ObjectConverterImpl; +import org.apache.jackrabbit.ocm.manager.objectconverter.impl.ProxyManagerImpl; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.impl.digester.DigesterMapperImpl; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.query.impl.QueryManagerImpl; +import org.apache.jackrabbit.ocm.repository.NodeUtil; +import org.apache.jackrabbit.ocm.version.Version; +import org.apache.jackrabbit.ocm.version.VersionIterator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Default implementation for + * {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager} + * + * @author Sandro Boehme + * @author Lombart + * Christophe + * @author Martin Koci + * @author Alexandru Popescu + */ +public class ObjectContentManagerImpl implements ObjectContentManager { + + private final static Logger log = LoggerFactory.getLogger(ObjectContentManagerImpl.class); + + protected Session session; + + protected Mapper mapper; + + protected QueryManager queryManager; + + protected ObjectConverter objectConverter; + + protected ObjectCache requestObjectCache; + + /** + * Creates a new ObjectContentManager that uses the passed in + * Mapper, and a Session + * + * @param mapper + * the Mapper component + * @param session + * The JCR session + */ + public ObjectContentManagerImpl(Session session, Mapper mapper) { + try { + this.session = session; + this.mapper = mapper; + // Use default setting for the following dependencies + DefaultAtomicTypeConverterProvider converterProvider = new DefaultAtomicTypeConverterProvider(); + Map atomicTypeConverters = converterProvider.getAtomicTypeConverters(); + this.queryManager = new QueryManagerImpl(mapper, atomicTypeConverters, session.getValueFactory()); + this.requestObjectCache = new RequestObjectCacheImpl(); + this.objectConverter = new ObjectConverterImpl(mapper, converterProvider, new ProxyManagerImpl(), requestObjectCache); + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to instantiate the object content manager", e); + + } + + } + + /** + * Creates a new ObjectContentManager based on a JCR session + * and some xml mapping files. + * + * @param session + * The JCR session + * @param xmlMappingFiles + * the JCR mapping files used mainly to create the + * Mapper component + */ + public ObjectContentManagerImpl(Session session, String[] xmlMappingFiles) { + try { + this.session = session; + this.mapper = new DigesterMapperImpl(xmlMappingFiles); + DefaultAtomicTypeConverterProvider converterProvider = new DefaultAtomicTypeConverterProvider(); + Map atomicTypeConverters = converterProvider.getAtomicTypeConverters(); + this.queryManager = new QueryManagerImpl(mapper, atomicTypeConverters, session.getValueFactory()); + this.requestObjectCache = new RequestObjectCacheImpl(); + this.objectConverter = new ObjectConverterImpl(mapper, converterProvider, new ProxyManagerImpl(), requestObjectCache); + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to instantiate the object content manager", e); + + } + + } + + /** + * Creates a new ObjectContentManager based on a JCR session + * and some xml mapping files. + * + * @param session + * The JCR session + * @param xmlMappingFiles + * the JCR mapping files used mainly to create the + * Mapper component + */ + public ObjectContentManagerImpl(Session session, InputStream[] xmlMappingFiles) { + try { + this.session = session; + this.mapper = new DigesterMapperImpl(xmlMappingFiles); + DefaultAtomicTypeConverterProvider converterProvider = new DefaultAtomicTypeConverterProvider(); + Map atomicTypeConverters = converterProvider.getAtomicTypeConverters(); + this.queryManager = new QueryManagerImpl(mapper, atomicTypeConverters, session.getValueFactory()); + this.requestObjectCache = new RequestObjectCacheImpl(); + this.objectConverter = new ObjectConverterImpl(mapper, converterProvider, new ProxyManagerImpl(), requestObjectCache); + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to instantiate the object content manager", e); + + } + + } + + /** + * Full constructor. + * + * @param mapper + * the Mapper component + * @param converter + * the ObjectConverter to be used internally + * @param queryManager + * the query manager to be used + * @param requestObjectCache + * the request object cache to be used + * @param session + * The JCR session + */ + public ObjectContentManagerImpl(Mapper mapper, ObjectConverter converter, QueryManager queryManager, + ObjectCache requestObjectCache, Session session) { + this.mapper = mapper; + this.session = session; + this.objectConverter = converter; + this.queryManager = queryManager; + this.requestObjectCache = requestObjectCache; + + } + + /** + * Sets the Mapper used by this object content manager. + * + * @param mapper + * mapping solver + */ + public void setMapper(Mapper mapper) { + this.mapper = mapper; + } + + /** + * Sets the ObjectConverter that is used internally by this + * object content manager. + * + * @param objectConverter + * the internal ObjectConverter + */ + public void setObjectConverter(ObjectConverter objectConverter) { + this.objectConverter = objectConverter; + } + + /** + * Sets the QueryManager used by the object content manager. + * + * @param queryManager + * a QueryManager + */ + public void setQueryManager(QueryManager queryManager) { + this.queryManager = queryManager; + } + + public void setRequestObjectCache(ObjectCache requestObjectCache) { + this.requestObjectCache = requestObjectCache; + } + + /** + * @see org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObject(java.lang.Class, + * java.lang.String) + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + * if the underlying repository has thrown a + * javax.jcr.RepositoryException + * @throws JcrMappingException + * if the mapping for the class is not correct + * @throws ObjectContentManagerException + * if the object cannot be retrieved from the path + */ + public Object getObject(String path) { + try { + if (!session.nodeExists(path)) { + return null; + } + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path, e); + } + + Object object = objectConverter.getObject(session, path); + requestObjectCache.clear(); + return object; + + } + + /** + * @param uuid the uuid of the backing jcr node + * @return the Object for uuid + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + * if the underlying repository has thrown a javax.jcr.RepositoryException + * @throws JcrMappingException if the mapping for the class is not correct + * @throws ObjectContentManagerException if the object cannot be retrieved from the path + * @throws IllegalArgumentException when the uuid is null or not a valid UUID + */ + public Object getObjectByUuid(String uuid) { + + try { + Node node = session.getNodeByIdentifier(uuid); + Object object = objectConverter.getObject(session, node.getPath()); + requestObjectCache.clear(); + return object; + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object with uuid : " + uuid, e); + } + + } + + /** + * + * @param path the object's absolute jcr path + * @param versionName the version that needs to be fetched + * @return the Object for path and version versionName or null if there is no jcr node for the specified + * path and versionName + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + * if the underlying repository has thrown a + * javax.jcr.RepositoryException + * @throws JcrMappingException + * if the mapping for the class is not correct + * @throws ObjectContentManagerException + * if the object cannot be retrieved from the path and versionName + */ + public Object getObject(String path, String versionName) { + String pathVersion; + try { + if (!session.nodeExists(path)) { + return null; + } + + Version version = this.getVersion(path, versionName); + pathVersion = version.getPath() + "/jcr:frozenNode"; + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path + " - version :" + versionName, e); + } + + Object object = objectConverter.getObject(session, pathVersion); + requestObjectCache.clear(); + return object; + } + + /** + * + * @param objectClass the object mapping class + * @param path the object's absolute jcr path + * @return the Object for path pr null if there is no jcr node at path + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + * if the underlying repository has thrown a + * javax.jcr.RepositoryException + * @throws JcrMappingException + * if the mapping for the class is not correct + * @throws ObjectContentManagerException + * if the object cannot be retrieved from the path + */ + public Object getObject(Class objectClass, String path) { + try { + if (!session.nodeExists(path)) { + return null; + } + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path, e); + } + + Object object = objectConverter.getObject(session, objectClass, path); + requestObjectCache.clear(); + return object; + + } + + public Object getObject(Class objectClass, String path, String versionName) { + String pathVersion = null; + try { + if (!session.nodeExists(path)) { + return null; + } + + Version version = this.getVersion(path, versionName); + pathVersion = version.getPath() + "/jcr:frozenNode"; + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path + " - version :" + versionName, e); + } + + Object object = objectConverter.getObject(session, objectClass, pathVersion); + requestObjectCache.clear(); + return object; + } + + public void retrieveAllMappedAttributes(Object object) { + objectConverter.retrieveAllMappedAttributes(session, object); + requestObjectCache.clear(); + + } + + public void retrieveMappedAttribute(Object object, String attributeName) { + objectConverter.retrieveMappedAttribute(session, object, attributeName); + requestObjectCache.clear(); + + } + + public void insert(Object object) { + String path = objectConverter.getPath(session, object); + + try { + if (session.nodeExists(path)) { + Node node = session.getNode(path); + if (!node.getDefinition().allowsSameNameSiblings()) { + throw new ObjectContentManagerException("Path already exists and it is not supporting the same name sibling : " + path); + } + } + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to insert the object at " + path, e); + } + + objectConverter.insert(session, object); + requestObjectCache.ready(path, object); + } + + public void update(Object object) { + String path = objectConverter.getPath(session, object); + try { + if (!session.nodeExists(path)) { + throw new ObjectContentManagerException("Path is not existing : " + path); + } else { + checkIfNodeLocked(path); + } + } catch (javax.jcr.RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to update", e); + } + + objectConverter.update(session, object); + // We do not use requestObjectCache.ready() here, + // because our changes might be rolled back later. + requestObjectCache.evict(path); + } + + public void remove(String path) { + try { + if (!session.nodeExists(path)) { + throw new ObjectContentManagerException("Path does not exist : " + path); + } else { + checkIfNodeLocked(path); + } + + Item item = session.getItem(path); + item.remove(); + requestObjectCache.evict(path); + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to remove the object at " + path); + } + } + + public void remove(Object object) { + this.remove(objectConverter.getPath(session, object)); + } + + + public void remove(Query query) { + try { + String jcrExpression = this.queryManager.buildJCRExpression(query); + log.debug("Remove Objects with expression: {}", jcrExpression); + + // Since only nodes are sufficient for us to remove, + // getObjects(query, language) method is not called here. + @SuppressWarnings("deprecation") + NodeIterator nodeIterator = getNodeIterator(jcrExpression, javax.jcr.query.Query.XPATH); + List nodes = new ArrayList(); + + while (nodeIterator.hasNext()) { + Node node = nodeIterator.nextNode(); + if (node == null) { + // node has been removed possibly by another thread during iterating through the results + continue; + } + log.debug("Remove node: {}", node.getPath()); + + // it is not possible to remove nodes from an NodeIterator + // So, we add the node found in a collection to remove them + // after + nodes.add(node); + } + + // Remove all collection nodes + for (int i = 0; i < nodes.size(); i++) { + Node node = (Node) nodes.get(i); + String path = node.getPath(); + checkIfNodeLocked(path); + try { + node.remove(); + } catch (javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException("Cannot remove node at path " + node.getPath() + " returned from query " + jcrExpression, re); + } + requestObjectCache.evict(path); + } + + } catch (InvalidQueryException iqe) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Invalid query expression", iqe); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object collection", e); + } + } + + public boolean objectExists(String path) { + try { + return session.nodeExists(path); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to check if the object exist", e); + } + } + + public boolean isPersistent(final Class clazz) { + + try { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(clazz); + if (classDescriptor == null) { + return false; + } + return true; + } catch (IncorrectPersistentClassException e) { + return false; + } + + } + + public Object getObject(Query query) { + String jcrExpression = this.queryManager.buildJCRExpression(query); + @SuppressWarnings("deprecation") + Collection result = getObjects(jcrExpression, javax.jcr.query.Query.XPATH); + + if (result.size() > 1) { + throw new ObjectContentManagerException("Impossible to get the object - the query returns more than one object"); + } + + return result.isEmpty() ? null : result.iterator().next(); + } + + @SuppressWarnings("deprecation") + public Collection getObjects(Query query) { + String jcrExpression = this.queryManager.buildJCRExpression(query); + return getObjects(jcrExpression, javax.jcr.query.Query.XPATH); + } + + public NodeIterator getNodes(Query query) { + String jcrExpression = this.queryManager.buildJCRExpression(query); + NodeIterator nodeIterator = getNodeIterator(jcrExpression, javax.jcr.query.Query.XPATH); + return nodeIterator; + } + + public Collection getObjects(Class objectClass, String path) throws ObjectContentManagerException { + final ClassDescriptor classDescriptorByClass = mapper.getClassDescriptorByClass(objectClass); + if (classDescriptorByClass == null) { + log.debug("Cannot get objects because no descriptor class exists for '{}'", objectClass.getClass().getName()); + return Collections.emptyList(); + } + try { + if (!session.nodeExists(path)) { + log.debug("Cannot get objects '{}' because no node exists at '{}'", objectClass.getClass().getName(), path); + return Collections.emptyList(); + } + Node parentNode = session.getNode(path).getParent(); + String nodeName = NodeUtil.getNodeName(path); + if (StringUtils.isBlank(nodeName)) { + nodeName = null; + } + NodeIterator candidates = parentNode.getNodes(); + List validated = new ArrayList(); + while (candidates.hasNext()) { + Node child = candidates.nextNode(); + if (nodeName != null && !child.getName().equals(nodeName)) { + continue; + } + if (child.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) { + if (child.getProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY).getString().equals(classDescriptorByClass.getClassName())) { + // the discriminator class name matches. This is an object we need + validated.add(child); + } + } else { + if (child.getPrimaryNodeType().getName().equals(classDescriptorByClass.getJcrType())) { + // nodetype matches + validated.add(child); + } + } + } + Collection result = new ArrayList(); + for (Node n : validated) { + Object object = objectConverter.getObject(session, n.getPath()); + if (object == null) { + log.debug("Could not get object for '{}'", n.getPath()); + continue; + } + // double check whether object is the same or a subclass of objectClass + if (objectClass.isAssignableFrom(object.getClass())) { + result.add(object); + } + } + return result; + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the objects at " + path, e); + } + + } + + public Iterator getObjectIterator(Query query) { + String jcrExpression = this.queryManager.buildJCRExpression(query); + log.debug("Get Object with expression: {}", jcrExpression); + @SuppressWarnings("deprecation") + NodeIterator nodeIterator = getNodeIterator(jcrExpression, javax.jcr.query.Query.XPATH); + + return new ObjectIterator(nodeIterator, this.objectConverter, this.session); + + } + + public Iterator getObjectIterator(String query, String language) { + log.debug("Get Object with expression: {}", query); + NodeIterator nodeIterator = getNodeIterator(query, language); + + return new ObjectIterator(nodeIterator, this.objectConverter, this.session); + } + + public Collection getObjects(String query, String language) { + try { + log.debug("Get Objects with expression [{}] and language {}", query, language); + + NodeIterator nodeIterator = getNodeIterator(query, language); + + List result = new ArrayList(); + while (nodeIterator.hasNext()) { + Node node = nodeIterator.nextNode(); + log.debug("Node found: {}", node.getPath()); + result.add(objectConverter.getObject(session, node.getPath())); + } + requestObjectCache.clear(); + return result; + } catch (InvalidQueryException iqe) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Invalid query expression", iqe); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object collection", e); + } + } + + private NodeIterator getNodeIterator(String query, String language) { + log.debug("Get Node Iterator with expression [{}] and language {}", query, language); + javax.jcr.query.Query jcrQuery; + try { + jcrQuery = session.getWorkspace().getQueryManager().createQuery(query, language); + QueryResult queryResult = jcrQuery.execute(); + NodeIterator nodeIterator = queryResult.getNodes(); + return nodeIterator; + } catch (InvalidQueryException iqe) { + throw new org.apache.jackrabbit.ocm.exception.InvalidQueryException(iqe); + } catch (RepositoryException re) { + throw new ObjectContentManagerException(re.getMessage(), re); + } + } + + public void checkin(String path) { + this.checkin(path, null); + } + + public void checkin(String path, String[] versionLabels) { + try { + Node node = (Node) session.getItem(path); + checkIfNodeLocked(node.getPath()); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + javax.jcr.version.Version newVersion = getVersionManager().checkin(path); + + if (versionLabels != null) { + VersionHistory versionHistory = getVersionManager().getVersionHistory(path); + for (int i = 0; i < versionLabels.length; i++) { + versionHistory.addVersionLabel(newVersion.getName(), versionLabels[i], false); + } + } + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (InvalidItemStateException iise) { + throw new ObjectContentManagerException("Cannot checking modified object at path " + path, iise); + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Impossible to checkin the object " + path, ve); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Cannot checkin unversionable node at path " + path, uroe); + } catch (LockException le) { + throw new VersionException("Cannot checkin locked node at path " + path, le); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to checkin the object " + path, e); + } + + } + + public void checkout(String path) { + Node node; + try { + node = (Node) session.getItem(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + getVersionManager().checkout(path); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Cannot checkout unversionable node at path " + path, uroe); + } catch (LockException le) { + throw new VersionException("Cannot checkout locked node at path " + path, le); + } catch (javax.jcr.RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to checkout the object " + path, e); + } + + } + + public void addVersionLabel(String path, String versionName, String versionLabel) { + try { + Node node = (Node) session.getItem(path); + checkIfNodeLocked(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + VersionHistory history = getVersionManager().getVersionHistory(path); + history.addVersionLabel(versionName, versionLabel, false); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Impossible to add a new version label to " + path + " - version name : " + versionName, ve); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to add a new version label to " + path + " - version name : " + versionName, uroe); + } catch (javax.jcr.RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public Version getVersion(String path, String versionName) { + try { + Node node = (Node) session.getItem(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + VersionHistory history = getVersionManager().getVersionHistory(path); + + return new Version(history.getVersion(versionName)); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("The version name " + versionName + "does not exist", ve); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to retrieve versions for path " + path, uroe); + } catch (javax.jcr.RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public String[] getVersionLabels(String path, String versionName) { + try { + Node node = (Node) session.getItem(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + VersionHistory history = getVersionManager().getVersionHistory(path); + javax.jcr.version.Version version = history.getVersion(versionName); + + return history.getVersionLabels(version); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Impossible to get the version labels : " + path + " - version name : " + versionName, ve); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to retrieve versions for path " + path, uroe); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public String[] getAllVersionLabels(String path) { + try { + Node node = session.getNode(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + VersionHistory history = getVersionManager().getVersionHistory(path); + + return history.getVersionLabels(); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to retrieve version history for path " + path, uroe); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public VersionIterator getAllVersions(String path) { + try { + Node node = session.getNode(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + VersionHistory history = getVersionManager().getVersionHistory(path); + + return new VersionIterator(history.getAllVersions()); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to retrieve version history for path " + path, uroe); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public Version getRootVersion(String path) { + try { + Node node = session.getNode(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + VersionHistory history = getVersionManager().getVersionHistory(path); + + return new Version(history.getRootVersion()); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to get the root version for the object " + path, uroe); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public Version getBaseVersion(String path) { + try { + Node node = session.getNode(path); + if (!node.isNodeType("mix:versionable")) { + throw new VersionException("The object " + path + "is not versionable"); + } + + return new Version(getVersionManager().getBaseVersion(path)); + } catch (ClassCastException cce) { + throw new ObjectContentManagerException("Cannot retrieve an object from a property path " + path); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Cannot retrieve an object at path " + path, pnfe); + } catch (UnsupportedRepositoryOperationException uroe) { + throw new VersionException("Impossible to get the base version for the object " + path, uroe); + } catch (javax.jcr.RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e); + } + } + + public Lock lock(final String absPath, final boolean isDeep, final boolean isSessionScoped) throws LockedException { + try { + + // Calling this method will throw exception if node is locked + // and this operation cant be done (exception translation) + checkIfNodeLocked(absPath); + + javax.jcr.lock.Lock lock = getLockManager().lock(absPath, isDeep, isSessionScoped, 0L, session.getUserID()); + + return new Lock(lock); + } catch (LockException e) { + // Only one case with LockException remains: if node is not + // mix:lockable, propably error in custom node types definitions + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Node of type is not type mix:lockable", e); + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e.getMessage(), e); + } + } + + public void unlock(final String absPath, final String lockToken) throws IllegalUnlockException { + String lockOwner = null; + try { + maybeAddLockToken(lockToken, absPath); + + Node node = getNode(absPath); + if (node.isLocked() == false) { + // Safe - if not locked return + return; + } + + javax.jcr.lock.Lock lock = getLockManager().getLock(absPath); + lockOwner = lock.getLockOwner(); + + getLockManager().unlock(absPath); + } catch (LockException e) { + // LockException if this node does not currently hold a lock (see + // upper code) + // or holds a lock for which this Session does not have the correct + // lock token + log.error("Cannot unlock path: " + absPath + " Jcr user: " + session.getUserID() + " has no lock token to do this. Lock was placed with user: " + lockOwner); + throw new IllegalUnlockException(lockOwner, absPath); + } catch (RepositoryException e) { + // This also catch UnsupportedRepositoryOperationException - we + // assume that implementation supports it (jackrabbit does) + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(e.getMessage(), e); + } + } + + public boolean isLocked(final String absPath) { + try { + final Node node = getNode(absPath); + return node.isLocked(); + } catch (RepositoryException e) { + // node.isLocked() RepositoryException if an error occurs. + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("An exception was thrown while checking the lock at path : " + absPath, e); + } + } + + public QueryManager getQueryManager() { + return this.queryManager; + } + + /** + * Throws {@link LockedException} id node is locked so alter nopde cannot be + * done + * + * @param absPath + * abs path to node + * @throws RepositoryException + * @throws LockedException + * if node is locked + */ + protected void checkIfNodeLocked(final String absPath) throws RepositoryException, LockedException { + Node node = getNode(absPath); + + // Node can hold lock or can be locked with precedencor + if (node.isLocked()) { + javax.jcr.lock.Lock lock = getLockManager().getLock(absPath); + String lockOwner = lock.getLockOwner(); + + if (!session.getUserID().equals(lockOwner)) { + final String path = lock.getNode().getPath(); + throw new LockedException(lockOwner, path); + } + } + } + + protected void maybeAddLockToken(final String lockToken, final String path) { + if (lockToken != null) { + // This user (this instance of PM) potentionally placed lock so + // session already has lock token + String[] lockTokens = null; + try { + lockTokens = getLockManager().getLockTokens(); + } catch (UnsupportedRepositoryOperationException ex) { + throw new LockedException(session.getUserID(), path); + } catch (RepositoryException ex) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(ex.getMessage(), ex); + } + if (lockTokens != null) { + for (int i = 0; i < lockTokens.length; i++) { + if (lockTokens[i].equals(lockToken)) { + // we are already holding a lock + break; + } + } + } else { + try { + getLockManager().addLockToken(lockToken); + } catch (UnsupportedRepositoryOperationException ex) { + throw new LockedException(session.getUserID(), path); + } catch (RepositoryException ex) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(ex.getMessage(), ex); + } + } + } + } + + protected Node getNode(final String absPath) throws PathNotFoundException, RepositoryException { + if (!session.nodeExists(absPath)) { + throw new ObjectContentManagerException("No object stored on path: " + absPath); + } + return session.getNode(absPath); + } + + public void logout() { + try { + log.debug("Logout. Persisting current session changes."); + this.session.save(); + this.session.logout(); + log.debug("Session closed"); + } catch (NoSuchNodeTypeException nsnte) { + throw new JcrMappingException("Cannot persist current session changes. An unknown node type was used.", nsnte); + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Cannot persist current session changes. Attempt to overwrite checked-in node", ve); + } catch (LockException le) { + throw new ObjectContentManagerException("Cannot persist current session changes. Violation of a lock detected", le); + } catch (javax.jcr.RepositoryException e) { + throw new ObjectContentManagerException("Cannot persist current session changes.", e); + } + } + + public void save() { + try { + this.session.save(); + } catch (NoSuchNodeTypeException nsnte) { + throw new JcrMappingException("Cannot persist current session changes. An unknown node type was used.", nsnte); + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Cannot persist current session changes. Attempt to overwrite checked-in node", ve); + } catch (LockException le) { + throw new ObjectContentManagerException("Cannot persist current session changes. Violation of a lock detected", le); + } catch (RepositoryException e) { + throw new ObjectContentManagerException("Cannot persist current session changes.", e); + } finally { + requestObjectCache.clear(); + } + } + + public Session getSession() { + return this.session; + } + + public void refresh(boolean keepChanges) { + try { + session.refresh(keepChanges); + } catch (RepositoryException e) { + throw new ObjectContentManagerException("Cannot refresh current session ", e); + } + } + + public void move(String srcPath, String destPath) { + try { + session.move(srcPath, destPath); + } catch (javax.jcr.nodetype.ConstraintViolationException cve) { + throw new ObjectContentManagerException("Cannot move the object from " + srcPath + " to " + destPath + "." + + " Violation of a nodetype or attempt to move under a property detected", cve); + + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Cannot move the object from " + srcPath + " to " + destPath + "." + " Parent node of source or destination is versionable and checked in ", + ve); + + } catch (javax.jcr.AccessDeniedException ade) { + throw new ObjectContentManagerException("Cannot move the object from " + srcPath + " to " + destPath + "." + " Session does not have access permissions", ade); + + } catch (javax.jcr.PathNotFoundException pnf) { + throw new ObjectContentManagerException("Cannot move the object from " + srcPath + " to " + destPath + "." + " Node at source or destination does not exist ", pnf); + + } catch (javax.jcr.ItemExistsException ie) { + throw new ObjectContentManagerException("Cannot move the object from " + srcPath + " to " + destPath + "." + " It might already exist at destination path.", ie); + + } catch (javax.jcr.lock.LockException le) { + throw new ObjectContentManagerException("Cannot move the object from " + srcPath + " to " + destPath + "." + "Violation of a lock detected", le); + + } catch (javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException("Cannot move the object from " + srcPath + " to " + destPath + ".", re); + } + } + + public void copy(String srcPath, String destPath) throws ObjectContentManagerException { + try { + if(StringUtils.isBlank(srcPath) || StringUtils.isBlank(destPath) || !srcPath.startsWith("/") || !destPath.startsWith("/")) { + throw new ObjectContentManagerException("scrPath " + srcPath + " or destPath " + destPath + " is not valid"); + } + // no check for existence needed, as handled by exceptions + Node srcNode = session.getNode(srcPath); + Node destNode; + if (session.nodeExists(destPath)) { + destNode = session.getNode(destPath); + } else { + // if parentDestNode cannot be found, just a PathNotFoundException is thrown + while (destPath.endsWith("/")) { + destPath = destPath.substring(0, destPath.length()-1); + } + int indexOfLastSlash = destPath.lastIndexOf("/"); + String parentDestPath = destPath.substring(0, indexOfLastSlash); + String destNodeName = destPath.substring(indexOfLastSlash + 1); + Node parentDestNode; + if (StringUtils.isBlank(parentDestPath)) { + parentDestNode = session.getRootNode(); + } else { + parentDestNode = session.getNode(parentDestPath); + } + destNode = parentDestNode.addNode(destNodeName, srcNode.getPrimaryNodeType().getName()); + } + copy(srcNode, destNode); + } catch (javax.jcr.nodetype.ConstraintViolationException cve) { + throw new ObjectContentManagerException("Cannot copy the object from " + srcPath + " to " + destPath + "." + + "Violation of a nodetype or attempt to copy under property detected ", cve); + + } catch (javax.jcr.version.VersionException ve) { + throw new VersionException("Cannot copy the object from " + srcPath + " to " + destPath + "." + "Parent node of source or destination is versionable and checked in ", + ve); + + } catch (javax.jcr.AccessDeniedException ade) { + throw new ObjectContentManagerException("Cannot copy the object from " + srcPath + " to " + destPath + "." + " Session does not have access permissions", ade); + + } catch (javax.jcr.PathNotFoundException pnf) { + throw new ObjectContentManagerException("Cannot copy the object from " + srcPath + " to " + destPath + "." + "Node at source or parent of destination does not exist ", pnf); + + } catch (javax.jcr.ItemExistsException ie) { + throw new ObjectContentManagerException("Cannot copy the object from " + srcPath + " to " + destPath + "." + "It might already exist at destination path.", ie); + + } catch (javax.jcr.lock.LockException le) { + throw new ObjectContentManagerException("Cannot copy the object from " + srcPath + " to " + destPath + "." + "Violation of a lock detected", le); + + } catch (javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException("Cannot copy the node from " + srcPath + " to " + destPath + ".", re); + } + } + + private LockManager getLockManager() throws UnsupportedRepositoryOperationException, RepositoryException { + return session.getWorkspace().getLockManager(); + } + + private VersionManager getVersionManager() throws UnsupportedRepositoryOperationException, RepositoryException { + return session.getWorkspace().getVersionManager(); + } + + /** + * Helper for copying scrNode (including properties & descendants) to destNode + * + * @param srcNode + * @param destNode + * @throws RepositoryException + */ + private void copy(Node srcNode, Node destNode) throws RepositoryException { + + NodeType[] mixinNodeTypes = srcNode.getMixinNodeTypes(); + for (int i = 0; i < mixinNodeTypes.length; i++) { + destNode.addMixin(mixinNodeTypes[i].getName()); + } + + for (PropertyIterator iter = srcNode.getProperties(); iter.hasNext(); ) { + Property property = iter.nextProperty(); + PropertyDefinition definition = property.getDefinition(); + if (!definition.isProtected()) { + if (definition.isMultiple()) { + destNode.setProperty(property.getName(), property.getValues(), property.getType()); + } else { + destNode.setProperty(property.getName(), property.getValue()); + } + } + } + + for (NodeIterator iter = srcNode.getNodes(); iter.hasNext(); ) { + Node node = iter.nextNode(); + Node child; + // check if the subnode is autocreated + if (!node.getDefinition().isAutoCreated() + && node.getIndex()==1 + && destNode.hasNode(node.getName())) { + child = destNode.getNode(node.getName()); + } else { + child = destNode.addNode(node.getName(), node.getPrimaryNodeType().getName()); + } + copy(node, child); + } + } + + public Collection getChildObjects(Class objectClass, String path) + throws ObjectContentManagerException { + + final ClassDescriptor classDescriptorByClass = mapper.getClassDescriptorByClass(objectClass); + if (classDescriptorByClass == null) { + return Collections.emptyList(); + } + try { + if (!session.nodeExists(path)) { + return Collections.emptyList(); + } + + long t1 = System.currentTimeMillis(); + + Node node = session.getNode(path); + NodeIterator children = node.getNodes(); + + long t2 = System.currentTimeMillis(); + + Collection result = new ArrayList(); + while (children.hasNext()) { + Node child = children.nextNode(); + Object object = objectConverter.getObject(session, objectClass, child.getPath()); + if (object == null) { + continue; + } + // double check whether object is the same or a subclass of objectClass + if (objectClass.isAssignableFrom(object.getClass())) { + result.add(object); + } + } + + long t3 = System.currentTimeMillis(); + return result; + + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the objects at " + path, e); + } + + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectContentManagerUtil.java b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectContentManagerUtil.java new file mode 100644 index 00000000..13804b73 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectContentManagerUtil.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; + + +/** +* Utility class for used in the object content manager and in the converters +* +* @author Lombart Christophe +*/ +public class ObjectContentManagerUtil +{ + + public static String getPath(Session session, BeanDescriptor beanDescriptor, Node parentNode) throws ObjectContentManagerException + { + try + { + String path = ""; + if (parentNode != null) + { + path += parentNode.getPath(); + } + return path + "/" + beanDescriptor.getJcrName(); + + } + catch (javax.jcr.RepositoryException e) + { + throw new RepositoryException(e); + } + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectIterator.java b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectIterator.java new file mode 100644 index 00000000..303dae18 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/impl/ObjectIterator.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.impl; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.RangeIterator; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; + + +/** + * ObjectIterator is a wrapper class for JCR NodeIterator, which returns + * mapped objects. + *

+ * This Iterator implementation does not support removing elements, therefore + * the {@link #remove()} method throws a UnsupportOperationException. + * + * @author Christophe Lombart + * + */ +public class ObjectIterator implements RangeIterator +{ + private NodeIterator nodeIterator; + + private Session session; + + private ObjectConverter objectConverter; + + /** + * Constructor + * + * @param iterator JCR node iterator + * @param converter The object converter + * @param session the JCR session + */ + public ObjectIterator(NodeIterator iterator, ObjectConverter converter, Session session) + { + nodeIterator = iterator; + objectConverter = converter; + this.session = session; + } + + /** + * @see java.util.Iterator#hasNext() + */ + public boolean hasNext() { + return nodeIterator.hasNext(); + } + + + /** + * @see java.util.Iterator#next() + */ + public Object next() { + try { + Node node = nodeIterator.nextNode(); + return objectConverter.getObject(session, node.getPath()); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Repository access issue trying to map node to an object", re); + } + } + + /** + * This Iterator implementation does not support removing elements, therefore + * this method always throws a UnsupportOperationException. + * + * @see java.util.Iterator#next() + */ + public void remove() { + throw new UnsupportedOperationException(); + } + + + /** + * @see javax.jcr.RangeIterator#skip(long) + */ + public void skip(long l) { + nodeIterator.skip(l); + } + + /** + * @see javax.jcr.RangeIterator#getSize() + */ + public long getSize() { + return nodeIterator.getSize(); + } + + /** + * @see javax.jcr.RangeIterator#getPosition() + */ + public long getPosition() { + return nodeIterator.getPosition(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/ObjectConverter.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/ObjectConverter.java new file mode 100644 index 00000000..fe5d5027 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/ObjectConverter.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + + +/** + * Convert any kind of beans into JCR nodes & properties + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +public interface ObjectConverter +{ + /** + * Insert the object + * + * @param session the JCR session + * @param object the object to insert + * @throws ObjectContentManagerException when it is not possible to insert the object + * + */ + public void insert(Session session, Object object) throws ObjectContentManagerException; + + /** + * Update the object + * + * @param session the JCR session + * @param object the object to update + * @throws ObjectContentManagerException when it is not possible to update the object + */ + public void update(Session session, Object object) throws ObjectContentManagerException; + + /** + * Retrieve an object from the JCR repo + * + * @param session The JCR session + * @param path the JCR path + * @return The object found or null when it does not exist at path + * + * @throws ObjectContentManagerException when it is not possible to retrieve the object + */ + public Object getObject(Session session, String path) throws ObjectContentManagerException; + + /** + * Retrieve an object from the JCR repo + * + * @param session The JCR session + * @param clazz The class assigned to the object to retrieve + * @param path the JCR path + * @return The object found or null when it does not exist at path + * + * @throws ObjectContentManagerException when it is not possible to retrieve the object + */ + public Object getObject(Session session, Class clazz, String path) throws ObjectContentManagerException; + + + /** + * Retrieve the specified attribute for the given persistent object. + * this attribute is either a bean or a collection. This method is usefull if the corresponding descriptor has an autoRetrieve="false" + * + * @param session The JCR session + * @param object The persistent object + * @param attributeName The name of the attribute to retrieve + */ + public void retrieveMappedAttribute(Session session, Object object, String attributeName); + + + /** + * Retrieve all mapped attributes for the given persistent object. + * + * @param session The JCR session + * @param object The persistent object + */ + public void retrieveAllMappedAttributes(Session session, Object object); + + /** + * Insert the object + * + * @param session the JCR session + * @param parentNode The parent node used to store the new JCR element (object) + * @param nodeName The node name used to store the object + * @param object the object to insert + * @throws ObjectContentManagerException when it is not possible to insert the object + */ + public void insert(Session session, Node parentNode, String nodeName, Object object) throws ObjectContentManagerException; + + /** + * Update the object + * + * @param session the JCR session + * @param objectNode The node to store the object + * @param object the object to update + * @throws ObjectContentManagerException when it is not possible to update the object + */ + public void update(Session session, Node objectNode, Object object) throws ObjectContentManagerException; + + /** + * Update the object + * + * @param session the JCR session + * @param parentNode The parent node used to store the new JCR element (object) + * @param nodeName The node name used to store the object + * @param object the object to update + * @throws ObjectContentManagerException when it is not possible to update the object + */ + public void update(Session session, Node parentNode, String nodeName, Object object) throws ObjectContentManagerException; + + /** + * Update the object + * + * @param session the JCR session + * @param uuId The UUID of the node to get updated. + * @param object the object to update + * @throws ObjectContentManagerException when it is not possible to update the object + */ + public void update(Session session, String uuId, Object object); + + /** + * Get the object JCR path + * + * @param session the JCR session + * @param object the object for which the path has to be retrieve + * @return the object JCR path + * @throws ObjectContentManagerException when it is not possible to retrieve the object path + */ + public String getPath(Session session , Object object) throws ObjectContentManagerException; + + public CollectionConverter getCollectionConverter(Session session, CollectionDescriptor collectionDescriptor); + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/ProxyManager.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/ProxyManager.java new file mode 100644 index 00000000..e18dd51f --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/ProxyManager.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +public interface ProxyManager { + + Object createBeanProxy(BeanConverter beanConverter, String path, Session session, Node parentNode, BeanDescriptor beanDescriptor, + ClassDescriptor beanClassDescriptor, Class beanClass, Object parent); + + Object createCollectionProxy(Session session, CollectionConverter collectionConverter, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass); + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/AbstractLazyLoader.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/AbstractLazyLoader.java new file mode 100644 index 00000000..fd57e117 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/AbstractLazyLoader.java @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.cglib.proxy.InvocationHandler; + +/** + * Parent Class of the OCM Lazy Loaders + * + * @author Stephane LANDELLE + */ +public abstract class AbstractLazyLoader implements InvocationHandler, Serializable { + + /** + * The logger + */ + private final static Logger log = LoggerFactory.getLogger(AbstractLazyLoader.class); + + /** + * The proxified instance + */ + private Object target = null; + + /** + * Indicate if the proxy has been loaded + */ + private boolean initialized = false; + + /** + * Return the proxified instance + * + * @return the proxified instance + */ + protected Object getTarget() { + if (!initialized) { + target = fetchTarget(); + initialized = true; + if (log.isDebugEnabled()) { + log.debug("Target loaded"); + } + } + return target; + } + + /** + * Fetch the proxified instance + * + * @return the proxified instance + */ + protected abstract Object fetchTarget(); + + /** + * Getter of property initialized + * + * @return initialized + */ + public boolean isInitialized() { + return initialized; + } + + /** + * Invoke proxy methods : delegate to proxified instance except for OcmProxy + * methods that are intercepted (because not concretely implemented) + * + * @see net.sf.cglib.proxy.InvocationHandler#invoke(java.lang.Object, + * java.lang.reflect.Method, java.lang.Object[]) + */ + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + if (!(proxy instanceof OcmProxy)) { + throw new IllegalArgumentException("proxy should implement OcmProxy"); + } + + // proxified methods without concrete implementation + if (args.length == 0) { + if (method.getName().equals("isInitialized")) { + return isInitialized(); + + } else if (method.getName().equals("fetch")) { + getTarget(); + return null; + } + } + + Object returnValue = null; + + if (Modifier.isPublic(method.getModifiers())) { + if (!method.getDeclaringClass().isInstance(getTarget())) { + throw new ClassCastException(getTarget().getClass().getName()); + } + returnValue = method.invoke(getTarget(), args); + } else { + if (!method.isAccessible()) { + method.setAccessible(true); + } + returnValue = method.invoke(getTarget(), args); + } + return returnValue == getTarget() ? proxy : returnValue; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/BeanLazyLoader.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/BeanLazyLoader.java new file mode 100644 index 00000000..d4b40d20 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/BeanLazyLoader.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; + +public class BeanLazyLoader extends AbstractLazyLoader { + + private volatile BeanConverter beanConverter; + private volatile Session session; + private volatile Node parentNode; + private volatile BeanDescriptor beanDescriptor; + private volatile ClassDescriptor beanClassDescriptor; + private volatile Class beanClass; + private volatile Object parent; + + public BeanLazyLoader(BeanConverter beanConverter, Session session, Node parentNode, BeanDescriptor beanDescriptor, + ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) { + this.beanConverter = beanConverter; + this.session = session; + this.parentNode = parentNode; + this.beanDescriptor = beanDescriptor; + this.beanClassDescriptor = beanClassDescriptor; + this.beanClass = beanClass; + this.parent = parent; + } + + @Override + protected Object fetchTarget() { + if (isInitialized()) { + throw new IllegalStateException("Proxy already initialized"); + } + + if (session == null) { + throw new IllegalStateException("Session null, probably because bean was serialized. Impossible to lazy load."); + } + + Object target = beanConverter.getObject(session, parentNode, beanDescriptor, beanClassDescriptor, beanClass, parent); + + clean(); + return target; + } + + private void clean() { + beanConverter = null; + session = null; + parentNode = null; + beanDescriptor = null; + beanClassDescriptor = null; + parent = null; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/CollectionLazyLoader.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/CollectionLazyLoader.java new file mode 100644 index 00000000..9f2d0875 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/CollectionLazyLoader.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +public class CollectionLazyLoader extends AbstractLazyLoader { + + private volatile CollectionConverter collectionConverter; + private volatile Session session; + private volatile Node collectionParentNode; + private volatile CollectionDescriptor collectionDescriptor; + private Class collectionFieldClass; + + public CollectionLazyLoader(CollectionConverter collectionConverter, Session session, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) { + this.collectionConverter = collectionConverter; + this.session = session; + this.collectionParentNode = parentNode; + this.collectionDescriptor = collectionDescriptor; + this.collectionFieldClass = collectionFieldClass; + } + + @Override + protected Object fetchTarget() { + if (isInitialized()) { + throw new IllegalStateException("Proxy already initialized"); + } + + if (session == null) { + throw new IllegalStateException("Session null, probably because bean was serialized. Impossible to lazy load."); + } + + ManageableObjects objects = collectionConverter.getCollection(session, collectionParentNode, collectionDescriptor, + collectionFieldClass); + Object target = objects.getObjects(); + clean(); + return target; + } + + private void clean() { + collectionConverter = null; + session = null; + collectionParentNode = null; + collectionDescriptor = null; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/ObjectConverterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/ObjectConverterImpl.java new file mode 100644 index 00000000..28a5cb04 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/ObjectConverterImpl.java @@ -0,0 +1,916 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import java.lang.reflect.Modifier; +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.ValueFormatException; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.nodetype.NodeType; +import javax.jcr.nodetype.NodeTypeManager; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.IncorrectPersistentClassException; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.ManagerConstant; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.cache.ObjectCache; +import org.apache.jackrabbit.ocm.manager.cache.impl.RequestObjectCacheImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjects; +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableObjectsUtil; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.DefaultCollectionConverterImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ManageableCollectionImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ManageableMapImpl; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerUtil; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ProxyManager; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.apache.jackrabbit.ocm.repository.NodeUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Default implementation for {@link ObjectConverterImpl} + * + * @author Lombart Christophe + * @author Alexandru Popescu + * @author Boni Gopalan + */ +public class ObjectConverterImpl implements ObjectConverter { + + private static final String DEFAULT_BEAN_CONVERTER = "org.apache.jackrabbit.ocm.manager.beanconverter.impl.DefaultBeanConverterImpl"; + + private final static Logger log = LoggerFactory.getLogger(ObjectConverterImpl.class); + + private Mapper mapper; + + protected AtomicTypeConverterProvider atomicTypeConverterProvider; + + private ProxyManager proxyManager; + + private SimpleFieldsHelper simpleFieldsHelp; + + private ObjectCache requestObjectCache; + + public ObjectConverterImpl() { + } + + /** + * Constructor + * + * @param mapper + * The mapper to used + * @param converterProvider + * The atomic type converter provider + * + */ + public ObjectConverterImpl(Mapper mapper, AtomicTypeConverterProvider converterProvider) { + this.mapper = mapper; + this.atomicTypeConverterProvider = converterProvider; + this.proxyManager = new ProxyManagerImpl(); + this.simpleFieldsHelp = new SimpleFieldsHelper(atomicTypeConverterProvider); + this.requestObjectCache = new RequestObjectCacheImpl(); + } + + /** + * Constructor + * + * @param mapper + * The mapper to used + * @param converterProvider + * The atomic type converter provider + * + */ + public ObjectConverterImpl(Mapper mapper, AtomicTypeConverterProvider converterProvider, ProxyManager proxyManager, ObjectCache requestObjectCache) { + this.mapper = mapper; + this.atomicTypeConverterProvider = converterProvider; + this.proxyManager = proxyManager; + this.simpleFieldsHelp = new SimpleFieldsHelper(atomicTypeConverterProvider); + this.requestObjectCache = requestObjectCache; + } + /** + * Set the Mapper used to solve mappings. + * + * @param mapper + * a Mapper + */ + public void setMapper(Mapper mapper) { + this.mapper = mapper; + } + + /** + * Sets the converter provider. + * + * @param converterProvider + * an AtomicTypeConverterProvider + */ + public void setAtomicTypeConverterProvider(AtomicTypeConverterProvider converterProvider) { + this.atomicTypeConverterProvider = converterProvider; + } + + public void insert(Session session, Object object) { + String path = this.getPath(session, object); + try { + String parentPath = NodeUtil.getParentPath(path); + String nodeName = NodeUtil.getNodeName(path); + Node parentNode = session.getNode(parentPath); + this.insert(session, parentNode, nodeName, object); + + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Impossible to insert the object at '" + path + "'", pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to insert the object at '" + path + + "'", re); + } + } + + + public void insert(Session session, Node parentNode, String nodeName, Object object) { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(object.getClass()); + + String jcrType = classDescriptor.getJcrType(); + if ((jcrType == null) || jcrType.equals("")) { + jcrType = ManagerConstant.NT_UNSTRUCTURED; + } + + Node objectNode; + try { + objectNode = parentNode.addNode(nodeName, jcrType); + } catch (NoSuchNodeTypeException nsnte) { + throw new JcrMappingException("Unknown node type " + jcrType + " for mapped class " + object.getClass(), nsnte); + } catch (RepositoryException re) { + throw new ObjectContentManagerException("Cannot create new node of type " + jcrType + " from mapped class " + + object.getClass(), re); + } + + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + String mixinTypeName = null; + try { + + // Add mixin types + if (null != classDescriptor.getJcrMixinTypes()) { + for (int i = 0; i < mixinTypes.length; i++) { + mixinTypeName = mixinTypes[i].trim(); + objectNode.addMixin(mixinTypeName); + } + } + + // Add mixin types defined in the associated interfaces + if (!classDescriptor.hasDiscriminator() && classDescriptor.hasInterfaces()) { + Iterator interfacesIterator = classDescriptor.getImplements().iterator(); + while (interfacesIterator.hasNext()) { + String interfaceName = (String) interfacesIterator.next(); + ClassDescriptor interfaceDescriptor = mapper + .getClassDescriptorByClass(ReflectionUtils.forName(interfaceName)); + objectNode.addMixin(interfaceDescriptor.getJcrType().trim()); + } + } + + // If required, add the discriminator node type + if (classDescriptor.hasDiscriminator()) { + addDiscriminatorProperty(object, objectNode); + } + + + } catch (NoSuchNodeTypeException nsnte) { + throw new JcrMappingException("Unknown mixin type " + mixinTypeName + " for mapped class " + object.getClass(), nsnte); + } catch (RepositoryException re) { + throw new ObjectContentManagerException("Cannot create new node of type " + jcrType + " from mapped class " + + object.getClass(), re); + } + + simpleFieldsHelp.storeSimpleFields(session, object, classDescriptor, objectNode); + insertBeanFields(session, object, classDescriptor, objectNode); + insertCollectionFields(session, object, classDescriptor, objectNode); + simpleFieldsHelp.refreshUuidPath(session, classDescriptor, objectNode, object); + } + + private void addDiscriminatorProperty(Object object, Node objectNode) + throws NoSuchNodeTypeException, VersionException, + ConstraintViolationException, LockException, RepositoryException, + ValueFormatException { + + try { + objectNode.setProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY, + ReflectionUtils.getBeanClass(object).getName()); + + } catch (Exception e) { + // if it is not possible to add the CLASS_NAME_PROPERTY due to strong constraints in the + // node type definition, try to add the Discriminator node type. + String mixinTypeName; + mixinTypeName = ManagerConstant.DISCRIMINATOR_NODE_TYPE; + objectNode.addMixin(mixinTypeName); + objectNode.setProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY, + ReflectionUtils.getBeanClass(object).getName()); + } + + } + + public void update(Session session, Object object) { + String path = this.getPath(session, object); + try { + String parentPath = NodeUtil.getParentPath(path); + String nodeName = NodeUtil.getNodeName(path); + Node parentNode = session.getNode(parentPath); + this.update(session, parentNode, nodeName, object); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Impossible to update the object at '" + path + "'", pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to update the object at '" + path + + "'", re); + } + } + + public void update(Session session, String uuId, Object object) { + try { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(ReflectionUtils.getBeanClass(object)); + Node objectNode = session.getNodeByIdentifier(uuId); + update(session, objectNode, object); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Impossible to update the object with UUID: " + uuId , pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to update the object with UUID: " + uuId, re); + } + } + + public void update(Session session, Node objectNode, Object object) { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(ReflectionUtils.getBeanClass(object)); + + checkNodeType(session, classDescriptor); + + checkCompatiblePrimaryNodeTypes(session, objectNode, classDescriptor, false); + + simpleFieldsHelp.storeSimpleFields(session, object, classDescriptor, objectNode); + updateBeanFields(session, object, classDescriptor, objectNode); + updateCollectionFields(session, object, classDescriptor, objectNode); + simpleFieldsHelp.refreshUuidPath(session, classDescriptor, objectNode, object); + } + + public void update(Session session, Node parentNode, String nodeName, Object object) { + try { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(ReflectionUtils.getBeanClass(object)); + Node objectNode = getNode(parentNode,classDescriptor,nodeName,object); + update(session, objectNode, object); + } catch (PathNotFoundException pnfe) { + throw new ObjectContentManagerException("Impossible to update the object: " + nodeName + " at node : " + parentNode, pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to update the object: " + + nodeName + " at node : " + parentNode, re); + } + } + + /** + * + * @param parentNode the parent node at which to look for the node element. + * @param nodeName the node name to look for + * @param object the data. + * @param classDescriptor + * @return The child node we are interested in. + */ + private Node getNode(Node parentNode, ClassDescriptor classDescriptor, String nodeName, Object object) throws RepositoryException{ + if (parentNode == null) return null; + NodeIterator nodes = parentNode.getNodes(nodeName); + if (nodes.getSize() == 1) return nodes.nextNode(); + if (classDescriptor.hasUUIdField()){ + String uuidFieldName = classDescriptor.getUuidFieldDescriptor().getFieldName(); + Object objUuid = ReflectionUtils.getNestedProperty(object, uuidFieldName); + String currentItemUuid = (objUuid == null) ? null : objUuid.toString(); + if (currentItemUuid != null){ + //The Node already exists so we need to update the existing node + //rather than to replace it. + return parentNode.getSession().getNodeByIdentifier(currentItemUuid); + } + else{ + throw new NullPointerException("Cannot locate the node to update since there is no UUID provided even though, " + classDescriptor.getClassName() + " has been mapped with a UUID field , " + uuidFieldName ); + } + + } + return parentNode.getNode(nodeName); + + } + + public Object getObject(Session session, String path) { + try { + if (!session.nodeExists(path)) { + return null; + } + + if (requestObjectCache.isCached(path)) + { + return requestObjectCache.getObject(path); + } + + ClassDescriptor classDescriptor; + Node node = session.getNode(path); + if (node.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) { + String className = node.getProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY).getValue().getString(); + classDescriptor = mapper.getClassDescriptorByClass(ReflectionUtils.forName(className)); + } else { + String nodeType = node.getPrimaryNodeType().getName(); + if (nodeType.equals(ManagerConstant.FROZEN_NODE_TYPE)) { + nodeType = node.getProperty(ManagerConstant.FROZEN_PRIMARY_TYPE_PROPERTY).getString(); + } + classDescriptor = mapper.getClassDescriptorByNodeType(nodeType); + } + + if (null == classDescriptor) { + throw new JcrMappingException("Impossible to find the classdescriptor for " + path + + ". There is no discriminator and associated JCR node type"); + } + + Object object = ReflectionUtils.newInstance(classDescriptor.getClassName()); + + if (! requestObjectCache.isCached(path)) + { + requestObjectCache.cache(path, object); + } + + simpleFieldsHelp.retrieveSimpleFields(session, classDescriptor, node, object); + retrieveBeanFields(session, classDescriptor, node, object, false); + retrieveCollectionFields(session, classDescriptor, node, object, false); + + requestObjectCache.ready(path, object); + + return object; + + } catch (PathNotFoundException pnfe) { + // HINT should never get here + throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path, re); + } + } + + public Object getObject(Session session, Class clazz, String path) + { + try { + if (!session.nodeExists(path)) { + return null; + } + + if (requestObjectCache.isCached(path)) + { + return requestObjectCache.getObject(path); + } + + ClassDescriptor classDescriptor = getClassDescriptor(clazz); + + checkNodeType(session, classDescriptor); + + Node node = session.getNode(path); + if (!classDescriptor.isInterface()) { + node = getActualNode(session,node); + checkCompatiblePrimaryNodeTypes(session, node, classDescriptor, true); + } + + ClassDescriptor alternativeDescriptor = null; + if (classDescriptor.usesNodeTypePerHierarchyStrategy()) { + if (node.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) { + String className = node.getProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY).getValue().getString(); + alternativeDescriptor = getClassDescriptor(ReflectionUtils.forName(className)); + } + } else { + if (classDescriptor.usesNodeTypePerConcreteClassStrategy()) { + String nodeType = node.getPrimaryNodeType().getName(); + if (!nodeType.equals(classDescriptor.getJcrType())) { + alternativeDescriptor = classDescriptor.getDescendantClassDescriptor(nodeType); + + // in case we an alternative could not be found by walking + // the class descriptor hierarchy, check whether we would + // have a descriptor for the node type directly (which + // may the case if the class descriptor hierarchy is + // incomplete due to missing configuration. See JCR-1145 + // for details. + if (alternativeDescriptor == null) { + alternativeDescriptor = mapper.getClassDescriptorByNodeType(nodeType); + } + } + } + } + + // if we have an alternative class descriptor, check whether its + // extends (or is the same) as the requested class. + if (alternativeDescriptor != null) { + Class alternativeClazz = ReflectionUtils.forName(alternativeDescriptor.getClassName()); + if (clazz.isAssignableFrom(alternativeClazz)) { + clazz = alternativeClazz; + classDescriptor = alternativeDescriptor; + } + } + + // ensure class is concrete (neither interface nor abstract) + if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { + throw new JcrMappingException( "Cannot instantiate non-concrete class " + clazz.getName() + + " for node " + path + " of type " + node.getPrimaryNodeType().getName()); + } + + Object object = ReflectionUtils.newInstance(classDescriptor.getClassName()); + + if (! requestObjectCache.isCached(path)) + { + requestObjectCache.cache(path, object); + } + + simpleFieldsHelp.retrieveSimpleFields(session, classDescriptor, node, object); + retrieveBeanFields(session, classDescriptor, node, object, false); + retrieveCollectionFields(session, classDescriptor, node, object, false); + + requestObjectCache.ready(path, object); + + return object; + } catch (PathNotFoundException pnfe) { + // HINT should never get here + throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path, re); + } + } + + public void retrieveAllMappedAttributes(Session session, Object object) { + String path = null; + try { + ClassDescriptor classDescriptor = getClassDescriptor(object.getClass()); + String pathFieldName = classDescriptor.getPathFieldDescriptor().getFieldName(); + path = (String) ReflectionUtils.getNestedProperty(object, pathFieldName); + Node node = session.getNode(path); + retrieveBeanFields(session, classDescriptor, node, object, true); + retrieveCollectionFields(session, classDescriptor, node, object, true); + + } catch (PathNotFoundException pnfe) { + + throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path, re); + } + } + + public void retrieveMappedAttribute(Session session, Object object, String attributeName) { + String path = null; + ClassDescriptor classDescriptor = null; + try { + classDescriptor = getClassDescriptor(object.getClass()); + String pathFieldName = classDescriptor.getPathFieldDescriptor().getFieldName(); + path = (String) ReflectionUtils.getNestedProperty(object, pathFieldName); + Node node = session.getNode(path); + BeanDescriptor beanDescriptor = classDescriptor.getBeanDescriptor(attributeName); + if (beanDescriptor != null) + { + this.retrieveBeanField(session, beanDescriptor, node, object, true); + } + // Check if the attribute is a collection + else + { + CollectionDescriptor collectionDescriptor = classDescriptor.getCollectionDescriptor(attributeName); + if (collectionDescriptor != null) + { + this.retrieveCollectionField(session, collectionDescriptor, node, object, true); + } + else + { + throw new ObjectContentManagerException("Impossible to retrieve the mapped attribute. The attribute '" + + attributeName + "' is not a bean or a collection for the class : " + classDescriptor.getClassName()); + } + } + + } catch (PathNotFoundException pnfe) { + + throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to get the object at " + path, re); + } + } + + /** + * Validates the node type used by the class descriptor. + * + * @param session + * the current session + * @param classDescriptor + * descriptor + * @throws JcrMappingException + * thrown if the node type is unknown + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + * thrown if an error occured in the underlying repository + */ + private void checkNodeType(Session session, ClassDescriptor classDescriptor) { + String jcrTypeName = null; + try { + + //Don't check the primary node type for interfaces. They are only associated to mixin node type + if (classDescriptor.isInterface()) { + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + for (int i = 0; i < mixinTypes.length; i++) { + jcrTypeName = mixinTypes[i]; + session.getWorkspace().getNodeTypeManager().getNodeType(jcrTypeName); + } + } else { + jcrTypeName = classDescriptor.getJcrType(); + if (jcrTypeName != null && !jcrTypeName.equals("")) { + session.getWorkspace().getNodeTypeManager().getNodeType(jcrTypeName); + } + } + } catch (NoSuchNodeTypeException nsnte) { + throw new JcrMappingException("Mapping for class '" + classDescriptor.getClassName() + + "' use unknown primary or mixin node type '" + jcrTypeName + "'"); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(re); + } + } + + /** + * Checks if the node type in the class descriptor is compatible with the + * specified node node type. + * + * @param session + * the current session + * @param node + * node against whose node type the compatibility is checked + * @param classDescriptor + * class descriptor + * @param checkVersionNode + * true if the check should continue in case the + * node is a version node, false if no + * check against version node should be performed + * + * @throws ObjectContentManagerException + * thrown if node types are incompatible + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + * thrown if an error occured in the underlying repository + */ + private void checkCompatiblePrimaryNodeTypes(Session session, Node node, ClassDescriptor classDescriptor, + boolean checkVersionNode) { + try { + NodeType nodeType = node.getPrimaryNodeType(); + + boolean compatible = checkCompatibleNodeTypes(nodeType, classDescriptor); + + if (!compatible && checkVersionNode && ManagerConstant.FROZEN_NODE_TYPE.equals(nodeType.getName())) { + NodeTypeManager ntMgr = session.getWorkspace().getNodeTypeManager(); + nodeType = ntMgr.getNodeType(node.getProperty(ManagerConstant.FROZEN_PRIMARY_TYPE_PROPERTY).getString()); + + compatible = checkCompatibleNodeTypes(nodeType, classDescriptor); + } + + if (!compatible) { + throw new ObjectContentManagerException("Cannot map object of type '" + classDescriptor.getClassName() + "'. Node type '" + + node.getPrimaryNodeType().getName() + "' does not match descriptor node type '" + + classDescriptor.getJcrType() + "'"); + } + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException(re); + } + } + + /** + * Node types compatibility check. + * + * @param nodeType + * target node type + * @param descriptor + * descriptor containing source node type + * @return true if nodes are considered compatible, + * false otherwise + */ + private boolean checkCompatibleNodeTypes(NodeType nodeType, ClassDescriptor descriptor) { + + //return true if node type is not used + if (descriptor.getJcrType() == null || descriptor.getJcrType().equals("")) { + return true; + } + + if (nodeType.getName().equals(descriptor.getJcrType())) { + return true; + } + + // Dirty horrible hack to get objects annotated with oak:Unstructured to access nt:unstructured nodes. + if(descriptor.getJcrType().equals("oak:Unstructured") && nodeType.getName().equals("nt:unstructured")){ + return true; + } + + NodeType[] superTypes = nodeType.getSupertypes(); + for (int i = 0; i < superTypes.length; i++) { + if (superTypes[i].getName().equals(descriptor.getJcrType())) { + return true; + } + } + + return false; + } + + /** + * @throws JcrMappingException + */ + public String getPath(Session session, Object object) { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(object.getClass()); + + final FieldDescriptor pathFieldDescriptor = classDescriptor.getPathFieldDescriptor(); + if (pathFieldDescriptor == null) { + throw new JcrMappingException( + "Class of type: " + + object.getClass().getName() + + " has no path mapping. Maybe attribute path=\"true\" for a field element of this class in mapping descriptor is missing " + + " or maybe it is defined in an ancestor class which has no mapping descriptor."); + } + String pathField = pathFieldDescriptor.getFieldName(); + + return (String) ReflectionUtils.getNestedProperty(object, pathField); + } + + private void retrieveBeanFields(Session session, ClassDescriptor classDescriptor, Node node, Object object, + boolean forceToRetrieve) { + Iterator beanDescriptorIterator = classDescriptor.getBeanDescriptors().iterator(); + while (beanDescriptorIterator.hasNext()) { + BeanDescriptor beanDescriptor = (BeanDescriptor) beanDescriptorIterator.next(); + this.retrieveBeanField(session, beanDescriptor, node, object, forceToRetrieve); + } + } + + + private void retrieveBeanField(Session session,BeanDescriptor beanDescriptor, Node node, Object object, boolean forceToRetrieve ) + { + if (!beanDescriptor.isAutoRetrieve() && !forceToRetrieve) + { + return; + } + + + String beanName = beanDescriptor.getFieldName(); + String beanPath = ObjectContentManagerUtil.getPath(session, beanDescriptor, node); + + Object bean = null; + if (requestObjectCache.isCached(beanPath)) + { + bean = requestObjectCache.getObject(beanPath); + ReflectionUtils.setNestedProperty(object, beanName, bean); + } + else + { + Class beanClass = ReflectionUtils.getPropertyType(object, beanName); + + String converterClassName = null; + if (null == beanDescriptor.getConverter() || "".equals(beanDescriptor.getConverter())) + { + converterClassName = DEFAULT_BEAN_CONVERTER; + } + else + { + converterClassName = beanDescriptor.getConverter(); + } + + Object[] param = {this.mapper, this, this.atomicTypeConverterProvider}; + BeanConverter beanConverter = (BeanConverter) ReflectionUtils.invokeConstructor(converterClassName, param); + if (beanDescriptor.isProxy()) + { + if (beanDescriptor.getJcrType() != null && !"".equals(beanDescriptor.getJcrType())) { + // If a mapped jcrType has been set, use it as proxy parent class instead of the bean property type. + // This way, we can handle proxies when bean property type is an interface. + try { + String className = mapper.getClassDescriptorByNodeType(beanDescriptor.getJcrType()).getClassName(); + if (log.isDebugEnabled()) { + log.debug("a mapped jcrType has been specified, switching from <" + beanClass + "> to <" + ReflectionUtils.forName(className)); + } + beanClass = ReflectionUtils.forName(className); + + } catch (IncorrectPersistentClassException e) { + if (log.isDebugEnabled()) { + log.debug(beanDescriptor.getClassDescriptor().getJcrType() + " is not mapped"); + } + } + } + + bean = proxyManager.createBeanProxy(beanConverter, beanConverter.getPath(session, beanDescriptor, node), session, node, beanDescriptor, mapper.getClassDescriptorByClass(beanClass), beanClass, bean); + } + else + { + bean = beanConverter.getObject(session, node, beanDescriptor, mapper.getClassDescriptorByClass(beanClass), beanClass, bean); + } + requestObjectCache.cache(beanPath, bean); + ReflectionUtils.setNestedProperty(object, beanName, bean); + } + + requestObjectCache.ready(beanPath, bean); + } + + private void retrieveCollectionFields(Session session, ClassDescriptor classDescriptor, Node parentNode, Object object, + boolean forceToRetrieve) { + Iterator collectionDescriptorIterator = classDescriptor.getCollectionDescriptors().iterator(); + while (collectionDescriptorIterator.hasNext()) { + CollectionDescriptor collectionDescriptor = (CollectionDescriptor) collectionDescriptorIterator.next(); + this.retrieveCollectionField(session, collectionDescriptor, parentNode, object, forceToRetrieve); + } + } + + private void retrieveCollectionField(Session session, CollectionDescriptor collectionDescriptor, Node parentNode, Object object, boolean forceToRetrieve) + { + if (!collectionDescriptor.isAutoRetrieve() && !forceToRetrieve) { + return; + } + + CollectionConverter collectionConverter = this.getCollectionConverter(session, collectionDescriptor); + Class collectionFieldClass = ReflectionUtils.getPropertyType(object, collectionDescriptor.getFieldName()); + if (collectionDescriptor.isProxy()) { + Object proxy = proxyManager.createCollectionProxy(session, collectionConverter, parentNode, + collectionDescriptor, collectionFieldClass); + ReflectionUtils.setNestedProperty(object, collectionDescriptor.getFieldName(), proxy); + } + else + { + ManageableObjects objects = collectionConverter.getCollection(session, parentNode, collectionDescriptor, collectionFieldClass); + if (objects==null) + { + ReflectionUtils.setNestedProperty(object, collectionDescriptor.getFieldName(), null); + } + else + { + // TODO: find another for managing custom ManageableObjects classes + if ( ! objects.getClass().equals(ManageableCollectionImpl.class) && + ! objects.getClass().equals(ManageableMapImpl.class)) + { + ReflectionUtils.setNestedProperty(object, collectionDescriptor.getFieldName(), objects); + } + else + { + ReflectionUtils.setNestedProperty(object, collectionDescriptor.getFieldName(), objects.getObjects()); + } + } + + } + + + } + + private void insertBeanFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) { + Iterator beanDescriptorIterator = classDescriptor.getBeanDescriptors().iterator(); + while (beanDescriptorIterator.hasNext()) { + BeanDescriptor beanDescriptor = (BeanDescriptor) beanDescriptorIterator.next(); + + if (!beanDescriptor.isAutoInsert()) { + continue; + } + + Object bean = ReflectionUtils.getNestedProperty(object, beanDescriptor.getFieldName()); + if (bean != null) + { + String converterClassName = null; + + if (null == beanDescriptor.getConverter() || "".equals(beanDescriptor.getConverter())) + { + converterClassName = DEFAULT_BEAN_CONVERTER; + } + else + { + converterClassName = beanDescriptor.getConverter(); + } + + Object[] param = {this.mapper, this, this.atomicTypeConverterProvider}; + BeanConverter beanConverter = (BeanConverter) ReflectionUtils.invokeConstructor(converterClassName, param); + beanConverter.insert(session, objectNode, beanDescriptor, mapper.getClassDescriptorByClass(bean.getClass()), bean, classDescriptor, object); + } + } + } + + + private void updateBeanFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) { + Iterator beanDescriptorIterator = classDescriptor.getBeanDescriptors().iterator(); + while (beanDescriptorIterator.hasNext()) + { + BeanDescriptor beanDescriptor = (BeanDescriptor) beanDescriptorIterator.next(); + if (!beanDescriptor.isAutoUpdate()) { + continue; + } + + Object bean = ReflectionUtils.getNestedProperty(object, beanDescriptor.getFieldName()); + + String converterClassName = null; + if (null == beanDescriptor.getConverter() || "".equals(beanDescriptor.getConverter())) + { + converterClassName = DEFAULT_BEAN_CONVERTER; + } + else + { + converterClassName = beanDescriptor.getConverter(); + } + + Object[] param = {this.mapper, this, this.atomicTypeConverterProvider }; + BeanConverter beanConverter = (BeanConverter) ReflectionUtils.invokeConstructor(converterClassName, param); + Class beanClass = ReflectionUtils.getPropertyType(object, beanDescriptor.getFieldName()); + // if the bean is null, remove existing node + if ((bean == null)) + { + + beanConverter.remove(session, objectNode, beanDescriptor, mapper.getClassDescriptorByClass(beanClass), bean, classDescriptor, object); + + } else + { + beanConverter.update(session, objectNode, beanDescriptor, mapper.getClassDescriptorByClass(beanClass), bean, classDescriptor, object); + } + + } + } + + private void insertCollectionFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) { + Iterator collectionDescriptorIterator = classDescriptor.getCollectionDescriptors().iterator(); + + while (collectionDescriptorIterator.hasNext()) { + CollectionDescriptor collectionDescriptor = (CollectionDescriptor) collectionDescriptorIterator.next(); + + if (!collectionDescriptor.isAutoInsert()) { + continue; + } + + CollectionConverter collectionConverter = this.getCollectionConverter(session, collectionDescriptor); + Object collection = ReflectionUtils.getNestedProperty(object, collectionDescriptor.getFieldName()); + ManageableObjects manageableCollection = ManageableObjectsUtil.getManageableObjects(collection); + + collectionConverter.insertCollection(session, objectNode, collectionDescriptor, manageableCollection); + } + } + + private void updateCollectionFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) { + Iterator collectionDescriptorIterator = classDescriptor.getCollectionDescriptors().iterator(); + + while (collectionDescriptorIterator.hasNext()) { + CollectionDescriptor collectionDescriptor = (CollectionDescriptor) collectionDescriptorIterator.next(); + if (!collectionDescriptor.isAutoUpdate()) { + continue; + } + + CollectionConverter collectionConverter = this.getCollectionConverter(session, collectionDescriptor); + Object collection = ReflectionUtils.getNestedProperty(object, collectionDescriptor.getFieldName()); + ManageableObjects manageableCollection = ManageableObjectsUtil.getManageableObjects(collection); + + collectionConverter.updateCollection(session, objectNode, collectionDescriptor, manageableCollection); + } + } + + + public CollectionConverter getCollectionConverter(Session session, CollectionDescriptor collectionDescriptor) { + String className = collectionDescriptor.getCollectionConverter(); + Map atomicTypeConverters = this.atomicTypeConverterProvider.getAtomicTypeConverters(); + if (className == null) { + return new DefaultCollectionConverterImpl(atomicTypeConverters, this, this.mapper); + } else { + return (CollectionConverter) ReflectionUtils.invokeConstructor(className, new Object[]{atomicTypeConverters, this, + this.mapper}); + } + + } + + private ClassDescriptor getClassDescriptor(Class beanClass) { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(beanClass); + if (null == classDescriptor) { + throw new JcrMappingException("Class of type: " + beanClass.getName() + + " is not JCR persistable. Maybe element 'class-descriptor' for this type in mapping file is missing"); + } + + return classDescriptor; + } + + private Node getActualNode(Session session, Node node) throws RepositoryException + { + NodeType type = node.getPrimaryNodeType(); + if (type.getName().equals("nt:versionedChild")) { + + String uuid = node.getProperty("jcr:childVersionHistory").getValue().getString(); + Node actualNode = session.getNodeByIdentifier(uuid); + String name = actualNode.getName(); + actualNode = session.getNodeByIdentifier(name); + + return actualNode; + } + + return node; + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/OcmProxy.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/OcmProxy.java new file mode 100644 index 00000000..9c3562f6 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/OcmProxy.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import java.io.Serializable; + +/** + * Interface implemented by lazy loading proxies + * + * @author Stephane LANDELLE + */ +public interface OcmProxy extends Serializable { + + /** + * Check is the proxy has been loaded + * + * @return true is the proxy has been loaded + */ + boolean isInitialized(); + + /** + * Force proxy fetching + */ + void fetch(); +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/OcmProxyUtils.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/OcmProxyUtils.java new file mode 100644 index 00000000..30d7b2f7 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/OcmProxyUtils.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +/** + * Utils class for proxy nandling + * + * @author Stephane LANDELLE + */ +public abstract class OcmProxyUtils { + + /** + * Check if an object is an OCM proxy + * + * @param object + * the Object to check + * @return true is the object is an OCM proxy + */ + public static boolean isProxy(Object object) { + return object instanceof OcmProxy; + } + + /** + * Check is an Object is not an unitialized OCM proxy + * @see OcmProxy.isInitialized() + * + * @param object + * the Object to check + * @return true if the object is not an OCM proxy or if it has already been + * initialized + */ + public static boolean isInitialized(Object object) { + if (!isProxy(object)) { + return true; + + } else { + return ((OcmProxy) object).isInitialized(); + } + } + + /** + * Force fetching of an abject + * + * @param the type of the object to fetch + * @param object the object to fetch + * @return the fetched object + */ + public static T fetch(T object) { + + if (isProxy(object)) { + ((OcmProxy) object).fetch(); + } + return object; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/ProxyManagerImpl.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/ProxyManagerImpl.java new file mode 100644 index 00000000..ba649886 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/ProxyManagerImpl.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; +import org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter; +import org.apache.jackrabbit.ocm.manager.objectconverter.ProxyManager; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; + +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.Enhancer; + +public class ProxyManagerImpl implements ProxyManager { + + /** + * @see org.apache.jackrabbit.ocm.manager.objectconverter.ProxyManager#createBeanProxy(javax.jcr.Session, + * org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter, + * java.lang.Class, java.lang.String) + */ + public Object createBeanProxy(BeanConverter beanConverter, String path, Session session, Node parentNode, + BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) { + try { + if (path == null || !session.itemExists(path)) { + return null; + } + } catch (RepositoryException e) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Impossible to check,if the object exits on " + path, e); + } + + Callback loader = new BeanLazyLoader(beanConverter, session, parentNode, beanDescriptor, beanClassDescriptor, beanClass, parent); + return Enhancer.create(beanClass, getInterfaces(beanClass), loader); + } + + /** + * @see org.apache.jackrabbit.ocm.manager.objectconverter.ProxyManager#createCollectionProxy(javax.jcr.Session, + * org.apache.jackrabbit.ocm.manager.collectionconverter.CollectionConverter, + * javax.jcr.Node, + * org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor, + * java.lang.Class) + */ + public Object createCollectionProxy(Session session, CollectionConverter collectionConverter, Node parentNode, + CollectionDescriptor collectionDescriptor, Class collectionFieldClass) { + + if (collectionConverter.isNull(session, parentNode, collectionDescriptor, collectionFieldClass)) { + return null; + } + + Callback loader = new CollectionLazyLoader(collectionConverter, session, parentNode, collectionDescriptor, collectionFieldClass); + return Enhancer.create(collectionFieldClass, getInterfaces(collectionFieldClass), loader); + } + + private Class[] getInterfaces(Class collectionFieldClass) { + + Class[] interfaces = null; + if (collectionFieldClass.isInterface()) { + // if collectionFieldClass is an interface, simply use it + interfaces = new Class[] { collectionFieldClass }; + } else { + // else, use all interfaces + interfaces = collectionFieldClass.getInterfaces(); + } + return (Class[]) ArrayUtils.add(interfaces, OcmProxy.class); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/SimpleFieldsHelper.java b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/SimpleFieldsHelper.java new file mode 100644 index 00000000..fbfaee80 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/manager/objectconverter/impl/SimpleFieldsHelper.java @@ -0,0 +1,459 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.objectconverter.impl; + +import java.util.Iterator; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.PathNotFoundException; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.ValueFormatException; +import javax.jcr.lock.LockException; +import javax.jcr.nodetype.ConstraintViolationException; +import javax.jcr.nodetype.NodeType; +import javax.jcr.nodetype.PropertyDefinition; +import javax.jcr.version.VersionException; + +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.ManagerConstant; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.NullTypeConverterImpl; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Helper class used to map simple fields. + * + * @author Lombart Christophe + * + */ +public class SimpleFieldsHelper +{ + + private final static Logger log = LoggerFactory.getLogger(SimpleFieldsHelper.class); + + private static final AtomicTypeConverter NULL_CONVERTER = new NullTypeConverterImpl(); + + private AtomicTypeConverterProvider atomicTypeConverterProvider; + + /** + * Constructor + * + * @param converterProvider The atomic type converter provider + * + */ + public SimpleFieldsHelper(AtomicTypeConverterProvider converterProvider) + { + this.atomicTypeConverterProvider = converterProvider; + } + + + /** + * Retrieve simple fields (atomic fields) + * + * @throws JcrMappingException + * @throws org.apache.jackrabbit.ocm.exception.RepositoryException + */ + public Object retrieveSimpleFields(Session session, ClassDescriptor classDescriptor, Node node, Object object) + { + Object initializedBean = object; + try { + Iterator fieldDescriptorIterator = classDescriptor.getFieldDescriptors().iterator(); + + if (classDescriptor.usesNodeTypePerHierarchyStrategy() && classDescriptor.hasDiscriminator()) + { + if (!node.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) + { + throw new ObjectContentManagerException("Class '" + + classDescriptor.getClassName() + + "' has not a discriminator property."); + } + } + while (fieldDescriptorIterator.hasNext()) { + FieldDescriptor fieldDescriptor = (FieldDescriptor) fieldDescriptorIterator.next(); + + String fieldName = fieldDescriptor.getFieldName(); + String propertyName = fieldDescriptor.getJcrName(); + + if (fieldDescriptor.isPath()) { + // HINT: lazy initialize target bean - The bean can be null + // when it is inline + if (null == initializedBean) { + initializedBean = ReflectionUtils.newInstance(classDescriptor.getClassName()); + } + + ReflectionUtils.setNestedProperty(initializedBean, fieldName, node.getPath()); + + } else { + if (fieldDescriptor.isUuid()) { + if (null == initializedBean) { + initializedBean = ReflectionUtils.newInstance(classDescriptor.getClassName()); + } + + ReflectionUtils.setNestedProperty(initializedBean, fieldName, node.getIdentifier()); + + } else { + initializedBean = retrieveSimpleField(classDescriptor, node, initializedBean, fieldDescriptor, fieldName, propertyName); + } + } + + } + } catch (ValueFormatException vfe) { + throw new ObjectContentManagerException( + "Cannot retrieve properties of object " + object + " from node " + node, vfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException( "Cannot retrieve properties of object " + object + + " from node " + node, re); + } + + return initializedBean; + } + + public Object refreshUuidPath(Session session, ClassDescriptor classDescriptor, Node node, Object object) + { + Object initializedBean = object; + try { + if (initializedBean == null) + { + return null; + } + + FieldDescriptor pathField = classDescriptor.getPathFieldDescriptor(); + if (pathField != null) + { + ReflectionUtils.setNestedProperty(initializedBean, pathField.getFieldName(), node.getPath()); + } + + FieldDescriptor uuidField = classDescriptor.getUuidFieldDescriptor(); + if (uuidField != null) + { + ReflectionUtils.setNestedProperty(initializedBean, uuidField.getFieldName(), node.getIdentifier()); + } + + } catch (ValueFormatException vfe) { + throw new ObjectContentManagerException( + "Cannot retrieve properties of object " + object + " from node " + node, vfe); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException( "Cannot retrieve properties of object " + object + + " from node " + node, re); + } + + return initializedBean; + } + + private Object retrieveSimpleField(ClassDescriptor classDescriptor, Node node, Object initializedBean, FieldDescriptor fieldDescriptor, String fieldName, String propertyName) throws RepositoryException, ValueFormatException, PathNotFoundException { + + Value propValue; + if (node.hasProperty(propertyName)) + { + propValue = node.getProperty(propertyName).getValue(); + } + else if (fieldDescriptor.getJcrDefaultValue() != null) + { + ValueFactory vf = node.getSession().getValueFactory(); + propValue = vf.createValue(fieldDescriptor.getJcrDefaultValue()); + } + else if (node.hasNode(propertyName)){ + Node childNode = node.getNode(propertyName); + NodeIterator nodes = childNode.getNodes(); + ValueFactory vf = node.getSession().getValueFactory(); + int s = 0; + while(nodes.hasNext() && s<=1000){ + s++; + nodes.next(); + } + propValue = vf.createValue(s); + } + else + { + PropertyDefinition propDef = getPropertyDefinition(node, propertyName); + + if (propDef != null && propDef.getDefaultValues() != null && propDef.getDefaultValues().length == 1) + { + if (log.isDebugEnabled()) { + log.debug("retrieveSimpleField: Use default value from property definition for missing mapped property " + propertyName + " of class '" + classDescriptor.getClassName() + "'"); + } + propValue = propDef.getDefaultValues()[0]; + } else + { + if (log.isDebugEnabled()) { + log.debug("retrieveSimpleField: No default value available for missing mapped property " + propertyName + " of class '" + classDescriptor.getClassName() + "'"); + } + propValue = null; + } + } + + // HINT: lazy initialize target bean - The bean can be null when it is inline + if (initializedBean == null) + { + + // if we do not have a value, we do nothing at all and just return null + if (propValue == null) + { + return null; + } + + // otherwise create the bean to set the value + initializedBean = ReflectionUtils.newInstance(classDescriptor.getClassName()); + } + + AtomicTypeConverter converter = getAtomicTypeConverter(fieldDescriptor, initializedBean, fieldName); + Object fieldValue = (propValue != null) ? converter.getObject(propValue) : null; + ReflectionUtils.setNestedProperty(initializedBean, fieldName, fieldValue); + + return initializedBean; + } + + public void storeSimpleFields(Session session, Object object, ClassDescriptor classDescriptor, Node objectNode) { + try { + ValueFactory valueFactory = session.getValueFactory(); + + Iterator fieldDescriptorIterator = classDescriptor.getFieldDescriptors().iterator(); + while (fieldDescriptorIterator.hasNext()) { + FieldDescriptor fieldDescriptor = (FieldDescriptor) fieldDescriptorIterator.next(); + + String fieldName = fieldDescriptor.getFieldName(); + String jcrName = fieldDescriptor.getJcrName(); + + // Of course, Path && UUID fields are not stored as property + if (fieldDescriptor.isPath() || fieldDescriptor.isUuid()) { + continue; + } + + storeSimpleField(object, objectNode, valueFactory, fieldDescriptor, fieldName, jcrName); + } + } catch (ValueFormatException vfe) { + throw new ObjectContentManagerException("Cannot persist properties of object " + object + ". Value format exception.", vfe); + } catch (VersionException ve) { + throw new ObjectContentManagerException("Cannot persist properties of object " + object + ". Versioning exception.", ve); + } catch (LockException le) { + throw new ObjectContentManagerException("Cannot persist properties of object " + object + " on locked node.", le); + } catch (ConstraintViolationException cve) { + throw new ObjectContentManagerException("Cannot persist properties of object " + object + ". Constraint violation.", cve); + } catch (RepositoryException re) { + throw new org.apache.jackrabbit.ocm.exception.RepositoryException("Cannot persist properties of object " + + object, re); + } + } + + + private void storeSimpleField(Object object, Node objectNode, ValueFactory valueFactory, FieldDescriptor fieldDescriptor, String fieldName, String jcrName) throws RepositoryException, PathNotFoundException, ValueFormatException, VersionException, LockException, ConstraintViolationException { + + boolean protectedProperty = isProtectedProperty(objectNode, fieldDescriptor, jcrName); + + if (!protectedProperty) + { // DO NOT TRY TO WRITE PROTECTED PROPERTIES + + Object fieldValue = ReflectionUtils.getNestedProperty(object, fieldName); + // if the value and if there is a default value for this field => set this default value + String defaultValue = fieldDescriptor.getJcrDefaultValue(); + if ((fieldValue == null) && (defaultValue != null)) + { + //Not sure that we have the attribute with the default value in all use cases + ReflectionUtils.setNestedProperty(object, fieldName, defaultValue); + fieldValue = ReflectionUtils.getNestedProperty(object, fieldName); + + } + AtomicTypeConverter converter = getAtomicTypeConverter(fieldDescriptor, object, fieldName); + Value value = converter.getValue(valueFactory, fieldValue); + + checkProperty(objectNode, fieldDescriptor, value); + objectNode.setProperty(jcrName, value); + } + + } + + + private boolean isProtectedProperty(Node objectNode, FieldDescriptor fieldDescriptor, String jcrName) throws RepositoryException, PathNotFoundException + { + // Return true if the property is defined as protected in the mapping file + if (fieldDescriptor.isJcrProtected()) + { + return true; + } + + // Check if the property is defined as protected in the JCR repo + + // 1. Check if the property already exists and may be queried + if (objectNode.hasProperty(jcrName)) + { + return objectNode.getProperty(jcrName).getDefinition().isProtected(); + } + + // 2. Find a definition for the property and checks its protected status + PropertyDefinition definition = getPropertyDefinition(objectNode, jcrName); + if (definition != null) + { + return definition.isProtected(); + } + + // This property is not defined in one of the node types + return false; + } + + private void checkProperty(Node objectNode, FieldDescriptor fieldDescriptor, Value value) throws RepositoryException { + if (value == null) + { + PropertyDefinition definition = getPropertyDefinition(objectNode, fieldDescriptor.getJcrName()); + if (definition != null) + { + if (definition.isMandatory() && !definition.isAutoCreated()) + { + throw new ObjectContentManagerException("Class of type:" + fieldDescriptor.getClassDescriptor().getClassName() + + " has property: " + fieldDescriptor.getFieldName() + " declared as JCR property: " + + fieldDescriptor.getJcrName() + " This property is mandatory but property in bean has value null"); + } + } + } + } + + private AtomicTypeConverter getAtomicTypeConverter(FieldDescriptor fd, Object object, String fieldName) { + Class fieldTypeClass = null; + // Check if an atomic converter is assigned to the field converter + String atomicTypeConverterClass = fd.getConverter(); + if (null != atomicTypeConverterClass) + { + return (AtomicTypeConverter) ReflectionUtils.newInstance(atomicTypeConverterClass); + } + else + { + // Get the default atomic converter in function of the classname + if (null != object) { + fieldTypeClass = ReflectionUtils.getPropertyType(object, fieldName); + } + + if (null != fieldTypeClass) { + return this.atomicTypeConverterProvider.getAtomicTypeConverter(fieldTypeClass); + } else { + return NULL_CONVERTER; + } + + } + } + + /** + * Returns the PropertyDefinition for the name property in + * the given node type. If the node type has no matching node type + * definition null is returned. + *

+ * This method scans as follows: If a PropertyDefinition with the exact + * name is found which is single-valued, this property definition is + * returned. Otherwise the first residual property definition which is + * single-valued is returned. Otherwise null is returned. + * + * @param nodeType The NodeType to search for matching node + * type definitions for the given property. + * @param propertyName The name of the property for which the + * PropertyDefinition is requested. + * + * @return The PropertyDefinition for the given property or + * null if none can be found in the type. + */ + private PropertyDefinition getPropertyDefinition(NodeType nodeType, String propertyName) { + PropertyDefinition[] pd = nodeType.getPropertyDefinitions(); + PropertyDefinition candidate = null; + for (int i=0; i < pd.length; i++) + { + // ignore multi-value properties + if (pd[i].isMultiple()) + { + continue; + } + + // if we have an exact match, use this and return + if (propertyName.equals(pd[i].getName())) + { + return pd[i]; + } + + // if we have a residual property definition consider as candidate + if (pd[i].getName() == null && candidate == null) + { + candidate = pd[i]; + } + } + + // return the potential residal candidate definition + return candidate; + } + + + /** + * Returns a PropertyDefinition for the given property name. + * This method first looks for a matching property definition in the + * primary node type and then in the list of mixin node types of the node. + * Only single-valued property definitions are considered by this method. + * If a definition whose name is the same as the propertyName + * is found, this definition is returned. Otherwise a residual property + * definition may be returned. + * + * @param node The Node whose primary and mixin node types are + * to be scanned for a single-valued property definition. + * @param propertyName The name of the property for which the property + * definition is to be returned. + * + * @return The PropertyDefinition for the named property or + * null if no single-valued exact or residual property + * definintion may be found in the node's primary or mixin node + * types. + * + * @throws RepositoryException If an error occurrs accessing the primary or + * mixin node types of the node. + */ + private PropertyDefinition getPropertyDefinition(Node node, String propertyName) throws RepositoryException { + + // try to find the definition in the primary node type + NodeType nt = node.getPrimaryNodeType(); + PropertyDefinition propDef = getPropertyDefinition(nt, propertyName); + + // return the definition if it is not residual + if (propDef != null && propDef.getName() != null) + { + return propDef; + } + + // otherwise look it up in any of the mixin node types + NodeType[] mixins = node.getMixinNodeTypes(); + for (int i = 0; mixins != null && i < mixins.length; i++) + { + PropertyDefinition candidate = getPropertyDefinition(mixins[i], propertyName); + + // use this property definition if not residual + if (candidate != null && candidate.getName() != null) + { + return propDef; + } + + // otherwise use this if we do not have a candidate yet + if (propDef == null) + { + propDef = candidate; + } + } + + // nothing found + return propDef; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/DescriptorReader.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/DescriptorReader.java new file mode 100644 index 00000000..b4621c3d --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/DescriptorReader.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper; + +import org.apache.jackrabbit.ocm.mapper.impl.AbstractMapperImpl; +import org.apache.jackrabbit.ocm.mapper.model.MappingDescriptor; + +public interface DescriptorReader { + + /** + * Load all class descriptors found in an classdescriptor definition. + * A classdescriptor definition can be a xml config file or annotations + * or another kind of resource which contain the classdescriptors + * + * DescriptorReader is an abstraction used to maximize reusability in {@link AbstractMapperImpl} + * + * @return a {@link MappingDescriptor} wich will contains a collection of classdescriptors + * + */ + public abstract MappingDescriptor loadClassDescriptors(); + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/Mapper.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/Mapper.java new file mode 100644 index 00000000..5a97ee44 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/Mapper.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper; + +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; + +/** + * This component read the mapping file and gives an access to the ClassDescriptors (the mapping object model) + * + * @author Lombart Christophe + * + */ +public interface Mapper +{ + /** + * Get the mapping defition to be used for a specific java bean + * @param clazz The java bean class + * @return The mapping class found for the desired java bean class + */ + public abstract ClassDescriptor getClassDescriptorByClass(Class clazz); + + /** + * Get the mapping defition to be used for a specific JCR node type + * @param jcrNodeType the jcr node type + * @return The mapping class found for the desired java bean class + */ + public abstract ClassDescriptor getClassDescriptorByNodeType(String jcrNodeType); +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/AbstractMapperImpl.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/AbstractMapperImpl.java new file mode 100644 index 00000000..91d5346c --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/AbstractMapperImpl.java @@ -0,0 +1,223 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl; + + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.jackrabbit.ocm.exception.IncorrectPersistentClassException; +import org.apache.jackrabbit.ocm.exception.InitMapperException; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.mapper.DescriptorReader; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.MappingDescriptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * Abstract class for {@link org.apache.jackrabbit.ocm.mapper.Mapper} + * + * @author Lombart Christophe + * @author : Boni Gopalan + * + * TODO : Add more reference tests. For exemple, the mapper has to check if the class used for the elements + * of a collectiondescriptor exists. For performance reasone, we can defined some optional validations. + */ +public abstract class AbstractMapperImpl implements Mapper { + protected static final Logger log = LoggerFactory.getLogger(AbstractMapperImpl.class); + + protected DescriptorReader descriptorReader; + protected MappingDescriptor mappingDescriptor; + protected Collection rootClassDescriptors = new ArrayList(); // contains the class descriptor which have not ancestors + + public void buildMapper() + { + mappingDescriptor = descriptorReader.loadClassDescriptors(); + mappingDescriptor.setMapper(this); + + if (null != this.mappingDescriptor) + { + List errors = new ArrayList(); + errors = solveReferences(errors); + errors = validateDescriptors(errors, rootClassDescriptors); + + if (!errors.isEmpty()) + { + throw new InitMapperException("Mapping descriptors contain errors." + + getErrorMessage(errors)); + } + } + else + { + throw new InitMapperException("No mappings were provided"); + } + + } + + + /** + * This method check class descriptor references (ancestor & implemented interfaces) : + * For each classdescriptor found, this method will check if the ancestor class and the implemented + * interfaces are also persistent or not. + * + * @param errors + * @return + */ + protected List solveReferences(List errors) { + for(Iterator it = this.mappingDescriptor.getClassDescriptorsByClassName().entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = (Map.Entry) it.next(); + ClassDescriptor cd = (ClassDescriptor) entry.getValue(); + + // Check if the ancestor is a persistent class + if (null != cd.getExtend() && !"".equals(cd.getExtend())) + { + ClassDescriptor superClassDescriptor = this.mappingDescriptor.getClassDescriptorByName(cd.getExtend()); + + if (null == superClassDescriptor) + { + // Just a debug info because we can have a non persisted ancestor class + if (log.isDebugEnabled()) { + log.debug("Cannot find mapping for class " + + cd.getExtend() + + " referenced as extends from " + + cd.getClassName()); + } + + // This is not necessary to keep a non persisted ancestor class + cd.setExtend(null); + + } + else + { + if (log.isDebugEnabled()) { + log.debug("Class " +cd.getClassName() + " extends " + cd.getExtend()); + } + cd.setSuperClassDescriptor(superClassDescriptor); + } + } + else + { + rootClassDescriptors.add(cd); + } + + // Check if the implemented interfaces are persistent classes + Set interfaces = cd.getImplements(); + Set mappedInterfaces = new HashSet(); + + if (interfaces.size() > 0) + { + for (Iterator iterator = interfaces.iterator(); iterator.hasNext();) + { + String interfaceName= (String) iterator.next(); + ClassDescriptor interfaceClassDescriptor = this.mappingDescriptor.getClassDescriptorByName(interfaceName); + + if (null == interfaceClassDescriptor) + { + // Just a debug info because we can have a non persisted interface reference + if (log.isDebugEnabled()) { + log.debug("Cannot find mapping for interface " + + interfaceName + + " referenced as implements from " + + cd.getClassName()); + } + + } + else + { + if (log.isDebugEnabled()) { + log.debug("Class " +cd.getClassName() + " implements " + interfaceName); + } + interfaceClassDescriptor.addDescendantClassDescriptor(cd); + mappedInterfaces.add(interfaceName); + } + + } + + cd.setImplements(mappedInterfaces); + } + + } + + return errors; + } + + /** + * Validate all class descriptors. + * This method validates the toplevel ancestors and after the descendants. + * Otherwise, we can have invalid settings in the class descriptors + * @param errors all errors found during the validation process + * @param classDescriptors the ancestor classdescriptors + * @return + */ + protected List validateDescriptors(List errors, Collection classDescriptors ) { + for(Iterator it = classDescriptors.iterator(); it.hasNext(); ) { + ClassDescriptor classDescriptor = (ClassDescriptor) it.next(); + try { + classDescriptor.afterPropertiesSet(); + if (classDescriptor.hasDescendants()) { + errors = validateDescriptors(errors, classDescriptor.getDescendantClassDescriptors()); + } + } + catch(JcrMappingException jme) { + log.warn("Mapping of class " + classDescriptor.getClassName() + " is invalid", jme); + errors.add(jme.getMessage()); + } + } + return errors; + } + + protected String getErrorMessage(List errors) { + final String lineSep = System.getProperty("line.separator"); + StringBuffer buf = new StringBuffer(); + for(Iterator it = errors.iterator(); it.hasNext();) { + buf.append(lineSep).append(it.next()); + } + + return buf.toString(); + } + + /** + * + * @see org.apache.jackrabbit.ocm.mapper.Mapper#getClassDescriptorByClass(java.lang.Class) + */ + public ClassDescriptor getClassDescriptorByClass(Class clazz) { + ClassDescriptor descriptor = mappingDescriptor.getClassDescriptorByName(clazz.getName()); + if (descriptor==null) { + throw new IncorrectPersistentClassException("Class of type: " + clazz.getName() + " has no descriptor."); + } + return descriptor ; + } + + /** + * @see org.apache.jackrabbit.ocm.mapper.Mapper#getClassDescriptorByNodeType(String) + */ + public ClassDescriptor getClassDescriptorByNodeType(String jcrNodeType) { + ClassDescriptor descriptor = mappingDescriptor.getClassDescriptorByNodeType(jcrNodeType); + if (descriptor==null) { + throw new IncorrectPersistentClassException("Node type: " + jcrNodeType + " has no descriptor."); + } + return descriptor ; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/AnnotationDescriptorReader.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/AnnotationDescriptorReader.java new file mode 100644 index 00000000..2c82ab14 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/AnnotationDescriptorReader.java @@ -0,0 +1,414 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.jackrabbit.ocm.exception.InitMapperException; +import org.apache.jackrabbit.ocm.mapper.DescriptorReader; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ImplementDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.MappingDescriptor; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Helper class that reads the xml mapping file and load all class descriptors into memory (object graph) + * + * @author Lombart Christophe + * @author : Boni Gopalan + * + */ +public class AnnotationDescriptorReader implements DescriptorReader +{ + private static final Logger log = LoggerFactory.getLogger(AnnotationDescriptorReader.class); + + List annotatedClassNames; + public AnnotationDescriptorReader(List annotatedClassNames) + { + this.annotatedClassNames = annotatedClassNames; + } + + + + public MappingDescriptor loadClassDescriptors() + { + MappingDescriptor mappingDescriptor = new MappingDescriptor(); + for (Class clazz : annotatedClassNames) { + + ClassDescriptor classDescriptor = buildClassDescriptor(mappingDescriptor, clazz); + mappingDescriptor.addClassDescriptor(classDescriptor); + } + return mappingDescriptor; + + } + + private ClassDescriptor buildClassDescriptor(MappingDescriptor mappingDescriptor, Class clazz) + { + ClassDescriptor classDescriptor = null; + + Node nodeAnnotation = (Node) clazz.getAnnotation(Node.class); + if (nodeAnnotation != null) + { + classDescriptor = createClassDescriptor(clazz, nodeAnnotation); + addImplementDescriptor(classDescriptor, clazz); + addAttributeDescriptors(mappingDescriptor, classDescriptor, clazz); + return classDescriptor; + } + else + { + throw new InitMapperException("The annotation @Node is not defined for the persistent class " + clazz.getName()); + } + + + + } + + private ClassDescriptor createClassDescriptor(Class clazz, Node nodeAnnotation) + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName(clazz.getName()); + classDescriptor.setJcrType(nodeAnnotation.jcrType()); + classDescriptor.setDiscriminator(nodeAnnotation.discriminator()); + if (nodeAnnotation.jcrSuperTypes() != null && ! nodeAnnotation.jcrSuperTypes().equals("")) + { + classDescriptor.setJcrSuperTypes(nodeAnnotation.jcrSuperTypes()); + } + + if (nodeAnnotation.jcrMixinTypes() != null && ! nodeAnnotation.jcrMixinTypes().equals("")) + { + classDescriptor.setJcrMixinTypes(nodeAnnotation.jcrMixinTypes()); + } + + Class ancestorClass = ReflectionUtils.getAncestorClass(clazz); + if (ancestorClass != null) + { + classDescriptor.setExtend(ancestorClass.getName()); + } + + // TODO : Can we still support the extend param in the annotation @Node if we are using + // the reflection to get the ancestor class ? (see the previous if) + if (nodeAnnotation.extend() != null && ! nodeAnnotation.extend().equals(Object.class)) + { + classDescriptor.setExtend(nodeAnnotation.extend().getName()); + } + + + classDescriptor.setAbstract(nodeAnnotation.isAbstract()||ReflectionUtils.isAbstractClass(clazz) ); + classDescriptor.setInterface(clazz.isInterface()); + return classDescriptor; + } + + private void addImplementDescriptor(ClassDescriptor classDescriptor, Class clazz) + { + Class[] interfaces = ReflectionUtils.getInterfaces(clazz); + for (int i = 0; i < interfaces.length; i++) { + ImplementDescriptor implementDescriptor = new ImplementDescriptor(); + implementDescriptor.setInterfaceName(interfaces[i].getName()); + classDescriptor.addImplementDescriptor(implementDescriptor); + } + + // TODO : Can we still support the annotation @Implement if we are using + // the reflection to get the list of the interfaces ? + Implement implementAnnotation = (Implement) clazz.getAnnotation(Implement.class); + if (implementAnnotation != null) + { + ImplementDescriptor implementDescriptor = new ImplementDescriptor(); + implementDescriptor.setInterfaceName(implementAnnotation.interfaceName().getName()); + classDescriptor.addImplementDescriptor(implementDescriptor); + } + + } + + /** + * Add FieldDescriptors, BeanDescriptors and CollectionDescriptors. + * The descriptots can be defined on the getter methods or on the field declation. + * + * @param mappingDescriptor The mapping descriptor + * @param classDescriptor the classdescriptor for which the descriptors have to be added + * @param clazz The associated class + */ + private void addAttributeDescriptors(MappingDescriptor mappingDescriptor, ClassDescriptor classDescriptor,Class clazz) { + + addDescriptorsFromFields(mappingDescriptor, classDescriptor, clazz); + addDescriptorsFromGetters(mappingDescriptor, classDescriptor, clazz); + } + + private void addDescriptorsFromFields(MappingDescriptor mappingDescriptor, ClassDescriptor classDescriptor, Class clazz) { + + java.lang.reflect.Field[] fields = getFields(clazz); + + for (int index = 0; index < fields.length; index++) + { + + Field fieldAnnotation = fields[index].getAnnotation(Field.class); + if (fieldAnnotation != null) { + addFieldDescriptor(classDescriptor, fields[index].getName(), fieldAnnotation); + } + + // Check if there is an Bean annotation + Bean beanAnnotation = fields[index].getAnnotation(Bean.class); + if (beanAnnotation != null) { + addBeanDescriptor(classDescriptor, fields[index].getName(), beanAnnotation); + } + + // Check if there is an Collection annotation + Collection collectionAnnotation = fields[index].getAnnotation(Collection.class); + if (collectionAnnotation != null) { + addCollectionDescriptor(mappingDescriptor, classDescriptor, fields[index], collectionAnnotation); + } + } + } + + private java.lang.reflect.Field[] getFields( Class clazz) { + java.lang.reflect.Field[] currentClassFields = clazz.getDeclaredFields(); + Class parentClass = clazz.getSuperclass(); + if (parentClass != null ) { + java.lang.reflect.Field[] parentClassFields = getFields(parentClass); + java.lang.reflect.Field[] union = concat(currentClassFields, parentClassFields); + currentClassFields = union; + } + return currentClassFields; + } + + private java.lang.reflect.Field[] concat(java.lang.reflect.Field[] A,java.lang.reflect.Field[] B) { + int aLen = A.length; + int bLen = B.length; + java.lang.reflect.Field[] C= new java.lang.reflect.Field[aLen+bLen]; + System.arraycopy(A, 0, C, 0, aLen); + System.arraycopy(B, 0, C, aLen, bLen); + return C; + } + + private void addDescriptorsFromGetters(MappingDescriptor mappingDescriptor, ClassDescriptor classDescriptor, Class clazz) { + BeanInfo beanInfo; + String fieldName = ""; + try { + beanInfo = Introspector.getBeanInfo(clazz); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { + fieldName = propertyDescriptor.getName(); + // Check if there is an Field annotation + Field fieldAnnotation = propertyDescriptor.getReadMethod().getAnnotation(Field.class); + if (fieldAnnotation != null) { + addFieldDescriptor(classDescriptor, propertyDescriptor.getName(), fieldAnnotation); + } + + // Check if there is an Bean annotation + Bean beanAnnotation = propertyDescriptor.getReadMethod().getAnnotation(Bean.class); + if (beanAnnotation != null) { + addBeanDescriptor(classDescriptor, propertyDescriptor.getName(), beanAnnotation); + } + + // Check if there is an Collection annotation + Collection collectionAnnotation = propertyDescriptor.getReadMethod().getAnnotation(Collection.class); + if (collectionAnnotation != null) { + + addCollectionDescriptor(mappingDescriptor, classDescriptor, + propertyDescriptor.getPropertyType().getDeclaredField(propertyDescriptor.getName()), + collectionAnnotation); + } + } + } catch (Exception e) { + throw new InitMapperException("Impossible to read the mapping descriptor from the getter for class : " + + clazz.toString() + + (fieldName == null ? "" : " for field : " + fieldName), e); + } + + } + + + private void addCollectionDescriptor(MappingDescriptor mappingDescriptor, ClassDescriptor descriptor, + java.lang.reflect.Field field, Collection collectionAnnotation) { + + Class targetClass = collectionAnnotation.elementClassName(); + CollectionDescriptor collectionDescriptor = new CollectionDescriptor(); + + collectionDescriptor.setFieldName(field.getName()); + + if (collectionAnnotation.jcrName() != null && ! collectionAnnotation.jcrName().equals("")) + { + collectionDescriptor.setJcrName(collectionAnnotation.jcrName()); + } + else + { + collectionDescriptor.setJcrName(field.getName()); + } + + collectionDescriptor.setProxy(collectionAnnotation.proxy()); + + collectionDescriptor.setAutoInsert(collectionAnnotation.autoInsert()); + collectionDescriptor.setAutoRetrieve(collectionAnnotation.autoRetrieve()); + collectionDescriptor.setAutoUpdate(collectionAnnotation.autoUpdate()); + collectionDescriptor.setCollectionClassName(field.getType().getName()); + if (! collectionAnnotation.elementClassName().equals(Object.class)) + { + collectionDescriptor.setElementClassName(collectionAnnotation.elementClassName().getName()); + } + else + { + setElementClassName(collectionDescriptor, field.getGenericType()); + } + + collectionDescriptor.setJcrElementName(collectionAnnotation.jcrElementName()); + + if (! collectionAnnotation.collectionClassName().equals(Object.class)) + { + collectionDescriptor.setCollectionClassName(collectionAnnotation.collectionClassName().getName()); + } + + collectionDescriptor.setCollectionConverter(collectionAnnotation.collectionConverter().getName()); + collectionDescriptor.setJcrType(collectionAnnotation.jcrType()); + collectionDescriptor.setJcrSameNameSiblings(collectionAnnotation.jcrSameNameSiblings()); + collectionDescriptor.setJcrAutoCreated(collectionAnnotation.jcrAutoCreated()); + collectionDescriptor.setJcrProtected(collectionAnnotation.jcrProtected()); + collectionDescriptor.setJcrOnParentVersion(collectionAnnotation.jcrOnParentVersion()); + collectionDescriptor.setJcrMandatory(collectionAnnotation.jcrMandatory()); + + + descriptor.addCollectionDescriptor(collectionDescriptor); + } + + + + private void setElementClassName(CollectionDescriptor collectionDescriptor, Type type) { + if (type instanceof ParameterizedType) + { + Type[] paramType = ((ParameterizedType) type).getActualTypeArguments(); + //TODO : change this condition. No sure if it will be all the time true. + // If only one type argument, the object is certainly a collection + if (paramType.length == 1) + { + collectionDescriptor.setElementClassName(paramType[0].toString().replace("class ", "").replace("interface ", "")); + + } + // either, it is certainly a map + else + { + collectionDescriptor.setElementClassName(paramType[1].toString().replace("class ", "").replace("interface ", "")); + } + + } + else + { + Type ancestorType = ((Class)type).getGenericSuperclass(); + if ( ancestorType!= null) + { + setElementClassName(collectionDescriptor,ancestorType); + } + else{ + collectionDescriptor.setElementClassName(Object.class.getName()); + } + } + } + + private void addBeanDescriptor(ClassDescriptor classDescriptor, String fieldName, Bean beanAnnotation) { + BeanDescriptor beanDescriptor = new BeanDescriptor(); + beanDescriptor.setFieldName(fieldName); + if (beanAnnotation.jcrName() != null && ! beanAnnotation.jcrName().equals("")) + { + beanDescriptor.setJcrName(beanAnnotation.jcrName()); + } + else + { + beanDescriptor.setJcrName(fieldName); + } + + beanDescriptor.setProxy(beanAnnotation.proxy()); + beanDescriptor.setConverter(beanAnnotation.converter().getName()); + beanDescriptor.setAutoInsert(beanAnnotation.autoInsert()); + beanDescriptor.setAutoRetrieve(beanAnnotation.autoRetrieve()); + beanDescriptor.setAutoUpdate(beanAnnotation.autoUpdate()); + beanDescriptor.setJcrType(beanAnnotation.jcrType()); + beanDescriptor.setJcrAutoCreated(beanAnnotation.jcrAutoCreated()); + beanDescriptor.setJcrMandatory(beanAnnotation.jcrMandatory()); + beanDescriptor.setJcrOnParentVersion(beanAnnotation.jcrOnParentVersion()); + beanDescriptor.setJcrProtected(beanAnnotation.jcrProtected()); + beanDescriptor.setJcrSameNameSiblings(beanAnnotation.jcrSameNameSiblings()); + + classDescriptor.addBeanDescriptor(beanDescriptor); + } + + + private void addFieldDescriptor(ClassDescriptor classDescriptor, String fieldName, Field fieldAnnotation) + { + + FieldDescriptor fieldDescriptor = new FieldDescriptor(); + fieldDescriptor.setFieldName(fieldName); + if ((fieldAnnotation.jcrName() != null) && (!fieldAnnotation.jcrName().equals(""))) + { + fieldDescriptor.setJcrName(fieldAnnotation.jcrName()); + } + else + { + fieldDescriptor.setJcrName(fieldName); + } + fieldDescriptor.setId(fieldAnnotation.id()); + fieldDescriptor.setPath(fieldAnnotation.path()); + fieldDescriptor.setUuid(fieldAnnotation.uuid()); + + // It is not possible to set a null value into an annotation attribute. + // If the converter == Object.class, it should be considered as null + if (! fieldAnnotation.converter().equals(Object.class)) + { + fieldDescriptor.setConverter(fieldAnnotation.converter().getName()); + } + + // It is not possible to set a null value into an annotation attribute. + // If the jcrDefaultValue value is an empty string => it should be considered as null + if ((fieldAnnotation.jcrDefaultValue() != null) && (!fieldAnnotation.jcrDefaultValue().equals(""))) + { + fieldDescriptor.setJcrDefaultValue(fieldAnnotation.jcrDefaultValue()); + } + + // It is not possible to set a null value into an annotation attribute. + // If the jcrValueConstraints value is an empty string => it should be considered as null + if ((fieldAnnotation.jcrValueConstraints() != null) && (!fieldAnnotation.jcrValueConstraints().equals(""))) + { + fieldDescriptor.setJcrValueConstraints(fieldAnnotation.jcrValueConstraints()); + } + + // It is not possible to set a null value into an annotation attribute. + // If the jcrProperty value is an empty string => it should be considered as null + if ((fieldAnnotation.jcrType() != null) && (!fieldAnnotation.jcrType().equals(""))) + { + fieldDescriptor.setJcrType(fieldAnnotation.jcrType()); + } + + fieldDescriptor.setJcrAutoCreated(fieldAnnotation.jcrAutoCreated()); + fieldDescriptor.setJcrMandatory(fieldAnnotation.jcrMandatory()); + fieldDescriptor.setJcrOnParentVersion(fieldAnnotation.jcrOnParentVersion()); + fieldDescriptor.setJcrProtected(fieldAnnotation.jcrProtected()); + fieldDescriptor.setJcrMultiple(fieldAnnotation.jcrMultiple()); + + //fieldDescriptor.setJcrType(value) + classDescriptor.addFieldDescriptor(fieldDescriptor); + } + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/AnnotationMapperImpl.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/AnnotationMapperImpl.java new file mode 100755 index 00000000..c8593861 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/AnnotationMapperImpl.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.util.List; + +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.impl.AbstractMapperImpl; + +/** + * An implementation of the OCM mapper that builds class descriptors based on + * the use of annotations on the underlying classes + * + * @author Philip Dodds + * + */ +public class AnnotationMapperImpl extends AbstractMapperImpl implements Mapper { + + + public AnnotationMapperImpl(List annotatedClassNames) + { + descriptorReader = new AnnotationDescriptorReader(annotatedClassNames); + this.buildMapper(); + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Bean.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Bean.java new file mode 100644 index 00000000..b32d0095 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Bean.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.DefaultBeanConverterImpl; + +/** + * @author Christophe Lombart + * + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD }) +@Inherited +public @interface Bean { + + String jcrName() default ""; + boolean proxy() default false; + Class converter() default DefaultBeanConverterImpl.class; + boolean autoInsert() default true; + boolean autoRetrieve() default true; + boolean autoUpdate() default true; + + // The folling annotation props are used to create jcr node type. + // There are not necessary for the mapping bean strategies. + String jcrType() default ""; + boolean jcrAutoCreated() default false; + boolean jcrMandatory() default false; + String jcrOnParentVersion() default "COPY"; + boolean jcrProtected() default false; + boolean jcrSameNameSiblings() default false; + + + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Collection.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Collection.java new file mode 100755 index 00000000..ae6a5d8f --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Collection.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.DefaultCollectionConverterImpl; + +/** + * Allows the annotation of getting methods to show that they reflect a child node in JCR + * + * @author Philip Dodds + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD }) +@Inherited +public @interface Collection { + + String jcrName() default ""; + + boolean proxy() default false; + + boolean autoRetrieve() default true; + + boolean autoUpdate() default true; + + boolean autoInsert() default true; + + // Use Object.class as default value + // because it is not possible to have a default null value in annotation field + Class elementClassName() default Object.class; + + String jcrElementName() default "collection-element"; + + Class collectionConverter() default DefaultCollectionConverterImpl.class; + + // Use Object.class as default value + // because it is not possible to have a default null value in annotation field + Class collectionClassName() default Object.class; + + String jcrType() default ""; + + boolean jcrAutoCreated() default false; + + boolean jcrMandatory() default false; + + String jcrOnParentVersion() default "COPY"; + + boolean jcrProtected() default false; + + boolean jcrSameNameSiblings() default false; + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Field.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Field.java new file mode 100755 index 00000000..944b0fae --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Field.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Allows the annotation of a getter method to show that it will be mapped to a JCR property + * + * @author Philip Dodds + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD }) +@Inherited +public @interface Field { + + String jcrName() default ""; + + boolean id() default false; + + boolean path() default false; + + boolean uuid() default false; + + // Use Object.class as default value + // because it is not possible to have a default null value in annotation field + Class converter() default Object.class; + + String jcrDefaultValue() default ""; + + String jcrValueConstraints() default ""; + + String jcrType() default ""; + + boolean jcrAutoCreated() default false; + + boolean jcrMandatory() default false; + + String jcrOnParentVersion() default "COPY"; + + boolean jcrProtected() default false; + + boolean jcrMultiple () default false; + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Implement.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Implement.java new file mode 100644 index 00000000..6323cc14 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Implement.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This annotation allow to defined the implement descriptor on the class + * level + * + * @author Lombart Christophe + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +@Inherited +public @interface Implement +{ + Class interfaceName(); +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Node.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Node.java new file mode 100755 index 00000000..bf3f74aa --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/annotation/Node.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Allows for the annotation of a Java class so mapping through OCM to a JCR node + * + * @author Philip Dodds + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +@Inherited +public @interface Node { + + String jcrType() default "nt:unstructured"; + String jcrSuperTypes() default ""; + String jcrMixinTypes() default ""; + // Define the extend setting in the mapping descriptor - Provide less flexibility if we use the java instrospection + Class extend() default Object.class; + + // Define the abstract setting in the mapping descriptor - Provide less flexibility if we use the java instrospection + boolean isAbstract() default false; + +// Define the inteface setting in the mapping descriptor - Provide less flexibility if we use the java instrospection + boolean isInterface() default false; + + // Discriminator is used when an object hierarchy tree is mapped into the same jcr node type + // TODO : try to drop it from the mapping strategy. it should be hidden in the persistence manager impl. + boolean discriminator() default true; + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/digester/DigesterDescriptorReader.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/digester/DigesterDescriptorReader.java new file mode 100644 index 00000000..387429b6 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/digester/DigesterDescriptorReader.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.digester; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import org.apache.commons.digester.Digester; +import org.apache.jackrabbit.ocm.exception.InitMapperException; +import org.apache.jackrabbit.ocm.mapper.DescriptorReader; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ImplementDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.MappingDescriptor; + +/** + * Helper class that reads the xml mapping file and load all class descriptors into memory (object graph) + * + * @author Lombart Christophe + * @author Alexandru Popescu + */ +public class DigesterDescriptorReader implements DescriptorReader +{ + private boolean validating = true; + private URL dtdResolver; + + private Collection configFileStreams = new ArrayList(); + + public DigesterDescriptorReader(InputStream stream) + { + configFileStreams.add(stream); + } + + public DigesterDescriptorReader(InputStream[] streams) + { + for (int i = 0; i < streams.length; i++) + { + configFileStreams.add(streams[i]); + } + + } + + public DigesterDescriptorReader(String xmlFile) + { + try + { + configFileStreams.add(new FileInputStream(xmlFile)); + } + catch (FileNotFoundException e) + { + throw new InitMapperException("Mapping file not found : " + xmlFile,e); + } + } + + public DigesterDescriptorReader(String[] xmlFiles) + { + + for (int i = 0; i < xmlFiles.length; i++) + { + try + { + configFileStreams.add(new FileInputStream(xmlFiles[i])); + } + + catch (FileNotFoundException e) + { + throw new InitMapperException("Mapping file not found : " + xmlFiles[i],e); + } + } + } + + + /** + * Set if the mapping should be validated. + * @param flag true if the mapping should be validated + */ + public void setValidating(boolean flag) { + this.validating= flag; + } + + public void setResolver(URL dtdResolver) { + this.dtdResolver = dtdResolver; + } + + /** + * Load all class descriptors found in the xml mapping file. + * + * @return a {@link MappingDescriptor} + * + */ + public MappingDescriptor loadClassDescriptors() + { + try + { + MappingDescriptor mappingDescriptor = new MappingDescriptor(); + for (Iterator iter = configFileStreams.iterator(); iter.hasNext();) + { + InputStream xmlMappingDescriptorFile = (InputStream) iter.next(); + + Digester digester = new Digester(); + digester.setValidating(this.validating); + if (null != this.dtdResolver) + { + digester.register("-//The Apache Software Foundation//DTD Repository//EN", + this.dtdResolver.toString()); + } + digester.setClassLoader(getClass().getClassLoader()); + + MappingDescriptor currentMappingDescriptor = new MappingDescriptor(); + digester.push(currentMappingDescriptor); + + + // -------------------------------------------------------------------------------- + // Rules used for the class-descriptor element + // -------------------------------------------------------------------------------- + digester.addObjectCreate("jackrabbit-ocm/class-descriptor", ClassDescriptor.class); + digester.addSetProperties("jackrabbit-ocm/class-descriptor"); + digester.addSetNext("jackrabbit-ocm/class-descriptor", "addClassDescriptor"); + + // -------------------------------------------------------------------------------- + // Rules used for the implement-descriptor element + // -------------------------------------------------------------------------------- + digester.addObjectCreate("jackrabbit-ocm/class-descriptor/implement-descriptor", ImplementDescriptor.class); + digester.addSetProperties("jackrabbit-ocm/class-descriptor/implement-descriptor"); + digester.addSetNext("jackrabbit-ocm/class-descriptor/implement-descriptor", "addImplementDescriptor"); + + // -------------------------------------------------------------------------------- + // Rules used for the field-descriptor element + // -------------------------------------------------------------------------------- + digester.addObjectCreate("jackrabbit-ocm/class-descriptor/field-descriptor", FieldDescriptor.class); + digester.addSetProperties("jackrabbit-ocm/class-descriptor/field-descriptor"); + digester.addSetNext("jackrabbit-ocm/class-descriptor/field-descriptor", "addFieldDescriptor"); + + // -------------------------------------------------------------------------------- + // Rules used for the bean-descriptor element + // -------------------------------------------------------------------------------- + digester.addObjectCreate("jackrabbit-ocm/class-descriptor/bean-descriptor", BeanDescriptor.class); + digester.addSetProperties("jackrabbit-ocm/class-descriptor/bean-descriptor"); + digester.addSetNext("jackrabbit-ocm/class-descriptor/bean-descriptor", "addBeanDescriptor"); + + // -------------------------------------------------------------------------------- + // Rules used for the collection-descriptor element + // -------------------------------------------------------------------------------- + digester.addObjectCreate("jackrabbit-ocm/class-descriptor/collection-descriptor", CollectionDescriptor.class); + digester.addSetProperties("jackrabbit-ocm/class-descriptor/collection-descriptor"); + digester.addSetNext("jackrabbit-ocm/class-descriptor/collection-descriptor", "addCollectionDescriptor"); + + currentMappingDescriptor = (MappingDescriptor) digester.parse(xmlMappingDescriptorFile); + + mappingDescriptor.getClassDescriptorsByClassName().putAll(currentMappingDescriptor.getClassDescriptorsByClassName()); + mappingDescriptor.getClassDescriptorsByNodeType().putAll(currentMappingDescriptor.getClassDescriptorsByNodeType()); + + } + return mappingDescriptor; + } + catch (Exception e) + { + throw new InitMapperException("Impossible to read the xml mapping descriptor file(s)", e); + } + } + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/digester/DigesterMapperImpl.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/digester/DigesterMapperImpl.java new file mode 100644 index 00000000..6c2137dc --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/impl/digester/DigesterMapperImpl.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.impl.digester; + + + +import java.io.InputStream; + +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.impl.AbstractMapperImpl; + +/** + * + * Digester implementation for {@link org.apache.jackrabbit.ocm.mapper.Mapper} + * + * @author Lombart Christophe + * @author Alexandru Popescu + */ +public class DigesterMapperImpl extends AbstractMapperImpl implements Mapper { + + + /** + * No-arg constructor. + */ + public DigesterMapperImpl() { + } + + /** + * Constructor + * + * @param xmlFile The xml mapping file to read + * + */ + public DigesterMapperImpl(String xmlFile) { + descriptorReader = new DigesterDescriptorReader(xmlFile); + this.buildMapper(); + } + + /** + * Constructor + * + * @param files a set of xml mapping files to read + * + */ + public DigesterMapperImpl(String[] files) { + descriptorReader = new DigesterDescriptorReader(files); + this.buildMapper(); + } + + /** + * Constructor + * + * @param stream The xml mapping file to read + */ + public DigesterMapperImpl(InputStream stream) { + descriptorReader = new DigesterDescriptorReader(stream); + this.buildMapper(); + } + + /** + * Constructor + * + * @param streams a set of mapping files to read + * + */ + public DigesterMapperImpl(InputStream[] streams) { + descriptorReader = new DigesterDescriptorReader(streams); + this.buildMapper(); + } + + + public DigesterMapperImpl(InputStream[] streams, boolean validate) { + descriptorReader = new DigesterDescriptorReader(streams); + DigesterDescriptorReader.class.cast(descriptorReader).setValidating(validate); + this.buildMapper(); + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/BeanDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/BeanDescriptor.java new file mode 100644 index 00000000..47296970 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/BeanDescriptor.java @@ -0,0 +1,277 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + +import org.apache.jackrabbit.ocm.manager.beanconverter.BeanConverter; + +/** + * BeanDescriptor is used by the mapper to read general information on a bean field + * + * @author Lombart Christophe + * @author Alexandru Popescu + */ +public class BeanDescriptor implements ChildNodeDefDescriptor, PropertyDefDescriptor { + private ClassDescriptor classDescriptor; + + private String fieldName; + private String jcrName; + private boolean proxy; + private boolean autoRetrieve = true; + private boolean autoUpdate = true; + private boolean autoInsert = true; + private String converter; + private BeanConverter beanConverter; + private String jcrType; + private boolean jcrAutoCreated; + private boolean jcrMandatory; + private String jcrOnParentVersion; + private boolean jcrProtected; + private boolean jcrSameNameSiblings; + private boolean jcrMultiple; + private String defaultPrimaryType; + + /** + * @return Returns the fieldName. + */ + public String getFieldName() { + return fieldName; + } + + /** + * @param fieldName The fieldName to set. + */ + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + /** + * @return Returns the jcrName. + */ + public String getJcrName() { + return jcrName; + } + + /** + * @param jcrName The jcrName to set. + */ + public void setJcrName(String jcrName) { + this.jcrName = jcrName; + } + + /** + * @return Returns the proxy. + */ + public boolean isProxy() { + return proxy; + } + + /** + * @param proxy The proxy to set. + */ + public void setProxy(boolean proxy) { + this.proxy = proxy; + } + + + public boolean isAutoInsert() { + return autoInsert; + } + + public void setAutoInsert(boolean autoInsert) { + this.autoInsert = autoInsert; + } + + public boolean isAutoRetrieve() { + return autoRetrieve; + } + + public void setAutoRetrieve(boolean autoRetrieve) { + this.autoRetrieve = autoRetrieve; + } + + public boolean isAutoUpdate() { + return autoUpdate; + } + + public void setAutoUpdate(boolean autoUpdate) { + this.autoUpdate = autoUpdate; + } + + + /** + * Get the BeanConverter fully qualified name or null + * if none specified by the bean descriptor. + * + * @return fully qualified class name or null + */ + public String getConverter() { + return this.converter; + } + + /** + * Sets the fully qualified name of a BeanConverter to be used. + * + * @param converterClass a fully qualified class name + */ + public void setConverter(String converterClass) { + this.converter = converterClass; + } + + + /** + * Getter for property jcrType. + * + * @return jcrType + */ + public String getJcrType() { + return jcrType; + } + + /** + * Setter for property jcrType. + * + * @param value jcrType + */ + public void setJcrType(String value) { + this.jcrType = value; + } + + /** Getter for property jcrAutoCreated. + * + * @return jcrAutoCreated + */ + public boolean isJcrAutoCreated() { + return jcrAutoCreated; + } + + /** Setter for property jcrAutoCreated. + * + * @param value jcrAutoCreated + */ + public void setJcrAutoCreated(boolean value) { + this.jcrAutoCreated = value; + } + + /** Getter for property jcrMandatory. + * + * @return jcrMandatory + */ + public boolean isJcrMandatory() { + return jcrMandatory; + } + + /** Setter for property jcrMandatory. + * + * @param value jcrMandatory + */ + public void setJcrMandatory(boolean value) { + this.jcrMandatory = value; + } + + /** Getter for property jcrOnParentVersion. + * + * @return jcrOnParentVersion + */ + public String getJcrOnParentVersion() { + return jcrOnParentVersion; + } + + /** Setter for property jcrOnParentVersion. + * + * @param value jcrOnParentVersion + */ + public void setJcrOnParentVersion(String value) { + this.jcrOnParentVersion = value; + } + + /** Getter for property jcrProtected. + * + * @return jcrProtected + */ + public boolean isJcrProtected() { + return jcrProtected; + } + + /** Setter for property jcrProtected. + * + * @param value jcrProtected + */ + public void setJcrProtected(boolean value) { + this.jcrProtected = value; + } + + /** Getter for property jcrSameNameSiblings. + * + * @return jcrSameNameSiblings + */ + public boolean isJcrSameNameSiblings() { + return jcrSameNameSiblings; + } + + /** Setter for property jcrSameNameSiblings. + * + * @param value jcrSameNameSiblings + */ + public void setJcrSameNameSiblings(boolean value) { + this.jcrSameNameSiblings = value; + } + + /** + * Getter for property jcrMultiple. + * + * @return jcrMultiple + */ + public boolean isJcrMultiple() { + return jcrMultiple; + } + + /** + * Setter for property jcrMultiple. + * + * @param value jcrMultiple + */ + public void setJcrMultiple(boolean value) { + this.jcrMultiple = value; + } + + /** + * @param descriptor + */ + public void setClassDescriptor(ClassDescriptor descriptor) { + this.classDescriptor = descriptor; + } + + /** + * @return Returns the classDescriptor. + */ + public ClassDescriptor getClassDescriptor() { + return classDescriptor; + } + + public String toString() { + + return "Bean Descriptor : " + this.fieldName; + } + + public String getDefaultPrimaryType() { + return defaultPrimaryType; + } + + public void setDefaultPrimaryType(String defaultPrimaryType) { + this.defaultPrimaryType = defaultPrimaryType; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ChildNodeDefDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ChildNodeDefDescriptor.java new file mode 100755 index 00000000..e84ffb8d --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ChildNodeDefDescriptor.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + +/** + * ChildNodeDefDescriptor is used by the node type management tools based on + * class descriptors to manage child node definitions + * + * @author Felix Meschberger + */ +public interface ChildNodeDefDescriptor { + + /** + * @return Returns the name of the property. + */ + String getJcrName(); + + /** + * @return Returns the child node type name. + */ + String getJcrType(); + + /** + * @return Whether the child node is auto created. + */ + boolean isJcrAutoCreated(); + + /** + * @return Whether the child node is mandatory. + */ + boolean isJcrMandatory(); + + /** + * @return What to do on parent version creation. + */ + String getJcrOnParentVersion(); + + /** + * @return Whether the child node is protected. + */ + boolean isJcrProtected(); + + /** + * @return Whether the child node definition allows for same name sibblings. + */ + boolean isJcrSameNameSiblings(); + + /** + * @return Whether the default not type to use when create new instances of this child + */ + String getDefaultPrimaryType(); + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ClassDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ClassDescriptor.java new file mode 100644 index 00000000..7413f67a --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ClassDescriptor.java @@ -0,0 +1,600 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * ClassDescriptor is used by the mapper to read general information on a class + * + * @author Lombart Christophe + * @author Alexandru Popescu + */ +public class ClassDescriptor { + + private static final Logger log = LoggerFactory.getLogger(ClassDescriptor.class); + + private static final String NODETYPE_PER_HIERARCHY = "nodetypeperhierarchy"; + private static final String NODETYPE_PER_CONCRETECLASS = "nodetypeperconcreteclass"; + + private MappingDescriptor mappingDescriptor; + private ClassDescriptor superClassDescriptor; + private HashSet descendantClassDescriptors = new HashSet(); + + private String className; + private String jcrType; + private String jcrSuperTypes; + private String[] jcrMixinTypes = new String[0]; + private FieldDescriptor idFieldDescriptor; + private FieldDescriptor pathFieldDescriptor; + private FieldDescriptor uuidFieldDescriptor; + + private Map fieldDescriptors = new HashMap(); + private Map beanDescriptors = new HashMap(); + private Map collectionDescriptors = new HashMap(); + + private Map fieldNames = new HashMap(); + + private String superClassName; + private String extendsStrategy; + private boolean isAbstract = false; + private boolean hasDescendant = false; + private boolean hasDiscriminator = true; + + + private boolean isInterface=false; + private Set interfaces = new HashSet(); + + + public void setAbstract(boolean flag) { + this.isAbstract = flag; + } + + public boolean isAbstract() { + return this.isAbstract; + } + + public void setInterface(boolean flag) { + this.isInterface = flag; + } + + public boolean isInterface() { + return isInterface; + } + + public boolean hasInterfaces() + { + return this.interfaces.size() > 0; + } + + public void setDiscriminator(boolean flag) + { + this.hasDiscriminator = flag; + } + + public boolean hasDiscriminator() { + return this.hasDiscriminator; + } + + public boolean usesNodeTypePerHierarchyStrategy() { + return NODETYPE_PER_HIERARCHY.equals(this.extendsStrategy); + } + + public boolean usesNodeTypePerConcreteClassStrategy() { + return NODETYPE_PER_CONCRETECLASS.equals(this.extendsStrategy); + } + /** + * @return Returns the className. + */ + public String getClassName() { + return className; + } + + /** + * @param className The className to set. + */ + public void setClassName(String className) { + this.className = className; + } + + /** + * @return Returns the jcrType. + */ + public String getJcrType() { + return jcrType; + } + + /** + * @param jcrType The jcrType to set. + */ + public void setJcrType(String jcrType) { + if (jcrType != null && ! jcrType.equals("")) + { + this.jcrType = jcrType; + } + } + + /** + * Add a new FielDescriptor + * @param fieldDescriptor the new field descriptor to add + */ + public void addFieldDescriptor(FieldDescriptor fieldDescriptor) { + fieldDescriptor.setClassDescriptor(this); + if (fieldDescriptor.isId()) { + this.idFieldDescriptor = fieldDescriptor; + } + if (fieldDescriptor.isPath()) { + this.pathFieldDescriptor = fieldDescriptor; + } + if (fieldDescriptor.isUuid()) { + this.uuidFieldDescriptor = fieldDescriptor; + } + + fieldDescriptors.put(fieldDescriptor.getFieldName(), fieldDescriptor); + fieldNames.put(fieldDescriptor.getFieldName(), fieldDescriptor.getJcrName()); + } + + public void addImplementDescriptor(ImplementDescriptor implementDescriptor) + { + interfaces.add(implementDescriptor.getInterfaceName()); + } + + /** + * Get the FieldDescriptor to used for a specific java bean attribute + * @param fieldName The java bean attribute name + * + * @return the {@link FieldDescriptor} found or null + */ + public FieldDescriptor getFieldDescriptor(String fieldName) { + return (FieldDescriptor) this.fieldDescriptors.get(fieldName); + } + + /** + * + * @return all {@link FieldDescriptor} defined in this ClassDescriptor + */ + public Collection getFieldDescriptors() { + return this.fieldDescriptors.values(); + } + + /** + * Add a new BeanDescriptor + * @param beanDescriptor the new bean descriptor to add + */ + + public void addBeanDescriptor(BeanDescriptor beanDescriptor) { + beanDescriptor.setClassDescriptor(this); + beanDescriptors.put(beanDescriptor.getFieldName(), beanDescriptor); + fieldNames.put(beanDescriptor.getFieldName(), beanDescriptor.getJcrName()); + } + + /** + * Get the BeanDescriptor to used for a specific java bean attribute + * @param fieldName The java bean attribute name + * + * @return the {@link BeanDescriptor} found or null + */ + public BeanDescriptor getBeanDescriptor(String fieldName) { + return (BeanDescriptor) this.beanDescriptors.get(fieldName); + } + + /** + * @return all {@link BeanDescriptor} defined in this ClassDescriptor + */ + public Collection getBeanDescriptors() { + return this.beanDescriptors.values(); + } + + /** + * Add a new CollectionDescriptor + * @param collectionDescriptor the new collection descriptor to add + */ + + public void addCollectionDescriptor(CollectionDescriptor collectionDescriptor) { + collectionDescriptor.setClassDescriptor(this); + collectionDescriptors.put(collectionDescriptor.getFieldName(), collectionDescriptor); + fieldNames.put(collectionDescriptor.getFieldName(), collectionDescriptor.getJcrName()); + } + + /** + * Get the CollectionDescriptor to used for a specific java bean attribute + * @param fieldName The java bean attribute name + * + * @return the {@link CollectionDescriptor} found or null + */ + public CollectionDescriptor getCollectionDescriptor(String fieldName) { + return (CollectionDescriptor) this.collectionDescriptors.get(fieldName); + } + + /** + * @return all {@link BeanDescriptor} defined in this ClassDescriptor + */ + public Collection getCollectionDescriptors() { + return this.collectionDescriptors.values(); + } + + /** + * @return the fieldDescriptor ID + */ + public FieldDescriptor getIdFieldDescriptor() { + if (null != this.idFieldDescriptor) { + return this.idFieldDescriptor; + } + + if (null != this.superClassDescriptor) { + return this.superClassDescriptor.getIdFieldDescriptor(); + } + + return null; + } + + /** + * @return the fieldDescriptor path + */ + public FieldDescriptor getPathFieldDescriptor() { + if (null != this.pathFieldDescriptor) { + return this.pathFieldDescriptor; + } + + if (null != this.superClassDescriptor) { + return this.superClassDescriptor.getPathFieldDescriptor(); + } + + return null; + } + + /** + * @return the fieldDescriptor path + */ + public FieldDescriptor getUuidFieldDescriptor() { + if (null != this.uuidFieldDescriptor) { + return this.uuidFieldDescriptor; + } + + if (null != this.superClassDescriptor) { + return this.superClassDescriptor.getUuidFieldDescriptor(); + } + + return null; + } + + /** + * Check if this class has an ID + * @return true if the class has an ID + */ + public boolean hasIdField() { + return (this.getIdFieldDescriptor() != null + && this.getIdFieldDescriptor().isId()); + } + + /** + * Check if this class has an UUID + * @return true if the class has an UUID + */ + public boolean hasUUIdField(){ + return (this.getUuidFieldDescriptor() != null + && this.getUuidFieldDescriptor().isUuid()); + + } + + /** + * Get the JCR name used for one of the object attributes + * @param fieldName the object attribute name (can be an atomic field, bean field or a collection field) + * @return the JCR name found + */ + public String getJcrName(String fieldName) { + String jcrName = (String) this.fieldNames.get(fieldName); + if (this.isInterface && jcrName == null) + { + return this.getJcrNameFromDescendants(this, fieldName); + } + + return jcrName; + } + + private String getJcrNameFromDescendants(ClassDescriptor classDescriptor, String fieldName ) + { + Iterator descendants = classDescriptor.getDescendantClassDescriptors().iterator(); + while (descendants.hasNext()) + { + ClassDescriptor descendant = (ClassDescriptor) descendants.next(); + String jcrName = (String) descendant.fieldNames.get(fieldName); + if(jcrName != null) + { + return jcrName; + } + return this.getJcrNameFromDescendants(descendant, fieldName); + } + return null; + + + } + + public Map getFieldNames() { + return this.fieldNames; + } + + /** Get the JCR node super types. + * + * @return jcrSuperTypes + */ + public String getJcrSuperTypes() { + return jcrSuperTypes; + } + + /** Setter for JCR super types. + * + * @param superTypes Comma separated list of JCR node super types + */ + public void setJcrSuperTypes(String superTypes) { + + if (superTypes != null && ! superTypes.equals("")) + { + this.jcrSuperTypes = superTypes; + } + + } + + /** + * Retrieve the mixin types. + * + * @return array of mixin types + */ + public String[] getJcrMixinTypes() { + return this.jcrMixinTypes; + } + + /** + * Sets a comma separated list of mixin types. + * + * @param mixinTypes command separated list of mixins + */ + public void setJcrMixinTypes(String[] mixinTypes) { + if (null != mixinTypes && mixinTypes.length == 1) { + jcrMixinTypes = mixinTypes[0].split(" *, *"); + } + } + public void setJcrMixinTypes(String mixinTypes) { + if (mixinTypes != null && ! mixinTypes.equals("")) + { + jcrMixinTypes = mixinTypes.split(" *, *"); + } + } + /** + * @return Returns the mappingDescriptor. + */ + public MappingDescriptor getMappingDescriptor() { + return mappingDescriptor; + } + + /** + * @param mappingDescriptor The mappingDescriptor to set. + */ + public void setMappingDescriptor(MappingDescriptor mappingDescriptor) { + this.mappingDescriptor = mappingDescriptor; + } + + /** + * Revisit information in this descriptor and fills in more. + */ + public void afterPropertiesSet() { + validateClassName(); + lookupSuperDescriptor(); + lookupInheritanceSettings(); + + } + + private void validateClassName() { + try { + ReflectionUtils.forName(this.className); + } catch (JcrMappingException e) { + throw new JcrMappingException("Class used in descriptor not found : " + className); + } + } + + + private void lookupSuperDescriptor() { + if (null != superClassDescriptor) { + + //Check some attributes defined on the ancestor class descriptor + this.hasDiscriminator = superClassDescriptor.hasDiscriminator(); + + // If there is no mixin type on the current classdescriptor, check if there is one on the ancestor class. + if(jcrMixinTypes == null || jcrMixinTypes.length == 0) + jcrMixinTypes = superClassDescriptor.jcrMixinTypes; + + if (! this.isInterface) + { + this.fieldDescriptors = mergeFields(this.fieldDescriptors, this.superClassDescriptor.getFieldDescriptors()); + this.beanDescriptors = mergeBeans(this.beanDescriptors, this.superClassDescriptor.getBeanDescriptors()); + this.collectionDescriptors = mergeCollections(this.collectionDescriptors, this.superClassDescriptor.getCollectionDescriptors()); + this.fieldNames.putAll(this.superClassDescriptor.getFieldNames()); + } + + } + } + + private void lookupInheritanceSettings() { + if ((null != this.superClassDescriptor) || (this.hasDescendants()) || this.hasInterfaces()) { + if (this.hasDiscriminator()) { + this.extendsStrategy = NODETYPE_PER_HIERARCHY; + } + else { + this.extendsStrategy = NODETYPE_PER_CONCRETECLASS; + } + } + } + + + /** + * @return return the super class name if defined in mapping, or + * null if not set + */ + public String getExtend() { + return this.superClassName; + } + + /** + * @param className + */ + public void setExtend(String className) { + if (className != null && className.length() == 0) { + className = null; + } + this.superClassName = className; + } + + /** + * @return Returns the superClassDescriptor. + */ + public ClassDescriptor getSuperClassDescriptor() { + return superClassDescriptor; + } + + public Collection getDescendantClassDescriptors() { + return this.descendantClassDescriptors; + } + + /** + * If the node type per concrete class strategy is used, we need to find a descendant class descriptor assigned to a node type + * This method is not used in other situation. + * + * @param nodeType the node type for which the classdescriptor is required + * @return the classdescriptor found or null + * + * @todo : maybe we have to review this implementation to have better performance. + */ + public ClassDescriptor getDescendantClassDescriptor(String nodeType) { + Iterator iterator = this.descendantClassDescriptors.iterator(); + while (iterator.hasNext()) { + ClassDescriptor descendantClassDescriptor = (ClassDescriptor) iterator.next(); + + if (nodeType.equals(descendantClassDescriptor.getJcrType())) { + return descendantClassDescriptor; + } + + if (descendantClassDescriptor.hasDescendants()) { + ClassDescriptor classDescriptor = descendantClassDescriptor.getDescendantClassDescriptor(nodeType); + if (classDescriptor != null) { + return classDescriptor; + } + } + } + return null; + } + + public void addDescendantClassDescriptor(ClassDescriptor classDescriptor) { + this.descendantClassDescriptors.add(classDescriptor); + this.hasDescendant = true; + } + + public boolean hasDescendants() { + return this.hasDescendant; + } + + /** + * @param superClassDescriptor The superClassDescriptor to set. + */ + public void setSuperClassDescriptor(ClassDescriptor superClassDescriptor) { + this.superClassDescriptor= superClassDescriptor; + superClassDescriptor.addDescendantClassDescriptor(this); + } + + + public Set getImplements() + { + return interfaces; + } + + public void setImplements(Set interfaces) + { + this.interfaces = interfaces; + } + + private Map mergeFields(Map existing, Collection superSource) { + if (null == superSource) { + return existing; + } + + Map merged = new HashMap(existing); + for(Iterator it = superSource.iterator(); it.hasNext();) { + FieldDescriptor fieldDescriptor = (FieldDescriptor) it.next(); + if (!merged.containsKey(fieldDescriptor.getFieldName())) { + merged.put(fieldDescriptor.getFieldName(), fieldDescriptor); + } +// else { +// log.warn("Field name conflict in " + this.className + " - field : " +fieldDescriptor.getFieldName() + " - this field name is also defined in the ancestor class : " + this.getExtend()); +// } + } + + return merged; + } + + + private Map mergeBeans(Map existing, Collection superSource) { + if (null == superSource) { + return existing; + } + + Map merged = new HashMap(existing); + for(Iterator it = superSource.iterator(); it.hasNext();) { + BeanDescriptor beanDescriptor = (BeanDescriptor) it.next(); + if (!merged.containsKey(beanDescriptor.getFieldName())) { + merged.put(beanDescriptor.getFieldName(), beanDescriptor); + } +// else { +// log.warn("Bean name conflict in " + this.className + " - field : " +beanDescriptor.getFieldName() + " - this field name is also defined in the ancestor class : " + this.getExtend()); +// } + } + + return merged; + } + + private Map mergeCollections(Map existing, Collection superSource) { + if (null == superSource) { + return existing; + } + + Map merged = new HashMap(existing); + for(Iterator it = superSource.iterator(); it.hasNext();) { + CollectionDescriptor collectionDescriptor = (CollectionDescriptor) it.next(); + if (!merged.containsKey(collectionDescriptor.getFieldName())) { + merged.put(collectionDescriptor.getFieldName(), collectionDescriptor); + } + } + + return merged; + } + + + + public String toString() { + return "Class Descriptor : " + this.getClassName(); + } +} diff --git a/src/java/org/apache/portals/graffito/jcr/mapper/model/CollectionDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/CollectionDescriptor.java similarity index 52% rename from src/java/org/apache/portals/graffito/jcr/mapper/model/CollectionDescriptor.java rename to src/main/java/org/apache/jackrabbit/ocm/mapper/model/CollectionDescriptor.java index c03c6a40..abfadd97 100644 --- a/src/java/org/apache/portals/graffito/jcr/mapper/model/CollectionDescriptor.java +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/CollectionDescriptor.java @@ -1,266 +1,249 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.mapper.model; - -/** - * - * CollectionDescriptor is used by the mapper to read general information on a collection field - * - * @author Lombart Christophe - * - */ -public class CollectionDescriptor -{ - - private String fieldName; - private String jcrName; - private String elementClassName; - private String collectionConverterClassName; - private String collectionClassName; - private boolean proxy; - private String jcrNodeType; - private boolean jcrAutoCreated; - private boolean jcrMandatory; - private String jcrOnParentVersion; - private boolean jcrProtected; - private boolean jcrSameNameSiblings; - - private ClassDescriptor classDescriptor; - - /** - * @return Returns the fieldName. - */ - public String getFieldName() - { - return fieldName; - } - /** - * @param fieldName The fieldName to set. - */ - public void setFieldName(String fieldName) - { - this.fieldName = fieldName; - } - /** - * @return Returns the jcrName. - */ - public String getJcrName() - { - return jcrName; - } - /** - * @param jcrName The jcrName to set. - */ - public void setJcrName(String jcrName) - { - this.jcrName = jcrName; - } - - - /** - * @return Returns the elementClassName. - */ - public String getElementClassName() - { - return elementClassName; - } - /** - * @param elementClassName The collection element class name to set. - * - */ - public void setElementClassName(String elementClassName) - { - this.elementClassName = elementClassName; - } - - /** - * @return Returns the proxy. - */ - public boolean isProxy() - { - return proxy; - } - /** - * @param proxy The proxy to set. - */ - public void setProxy(boolean proxy) - { - this.proxy = proxy; - } - - /** - * - * @return The collection converter class name - */ - public String getCollectionConverterClassName() - { - return collectionConverterClassName; - } - - /** - * Set the collection converter class name - * @param collectionConverterClassName The converter to set - */ - public void setCollectionConverterClassName(String collectionConverterClassName) - { - this.collectionConverterClassName = collectionConverterClassName; - } - - /** - * - * @return the collection class name (can be also a Map) - */ - public String getCollectionClassName() - { - return collectionClassName; - } - - /** - * Set the collection class name. - * This collection class has to implement {@link org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection} - * @param collectionClassName The collection class name to set - */ - public void setCollectionClassName(String collectionClassName) - { - this.collectionClassName = collectionClassName; - } - - /** - * - * @return The associated class descriptor - */ - public ClassDescriptor getClassDescriptor() - { - return classDescriptor; - } - - /** - * Set the associated class descriptor - * @param classDescriptor the class descriptor to set - */ - public void setClassDescriptor(ClassDescriptor classDescriptor) - { - this.classDescriptor = classDescriptor; - } - - /** Getter for property jcrNodeType. - * - * @return jcrNodeType - */ - public String getJcrNodeType() - { - return jcrNodeType; - } - - /** Setter for property jcrNodeType. - * - * @param value jcrNodeType - */ - public void setJcrNodeType(String value) - { - this.jcrNodeType = value; - } - - /** Getter for property jcrAutoCreated. - * - * @return jcrAutoCreated - */ - public boolean isJcrAutoCreated() - { - return jcrAutoCreated; - } - - /** Setter for property jcrAutoCreated. - * - * @param value jcrAutoCreated - */ - public void setJcrAutoCreated(boolean value) - { - this.jcrAutoCreated = value; - } - - /** Getter for property jcrMandatory. - * - * @return jcrMandatory - */ - public boolean isJcrMandatory() - { - return jcrMandatory; - } - - /** Setter for property jcrMandatory. - * - * @param value jcrMandatory - */ - public void setJcrMandatory(boolean value) - { - this.jcrMandatory = value; - } - - /** Getter for property jcrOnParentVersion. - * - * @return jcrOnParentVersion - */ - public String getJcrOnParentVersion() - { - return jcrOnParentVersion; - } - - /** Setter for property jcrOnParentVersion. - * - * @param value jcrOnParentVersion - */ - public void setJcrOnParentVersion(String value) - { - this.jcrOnParentVersion = value; - } - - /** Getter for property jcrProtected. - * - * @return jcrProtected - */ - public boolean isJcrProtected() - { - return jcrProtected; - } - - /** Setter for property jcrProtected. - * - * @param value jcrProtected - */ - public void setJcrProtected(boolean value) - { - this.jcrProtected = value; - } - - /** Getter for property jcrSameNameSiblings. - * - * @return jcrSameNameSiblings - */ - public boolean isJcrSameNameSiblings() - { - return jcrSameNameSiblings; - } - - /** Setter for property jcrSameNameSiblings. - * - * @param value jcrSameNameSiblings - */ - public void setJcrSameNameSiblings(boolean value) - { - this.jcrSameNameSiblings = value; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + + +/** + * + * CollectionDescriptor is used by the mapper to read general information on a collection field + * + * @author Lombart Christophe + * + */ +public class CollectionDescriptor implements ChildNodeDefDescriptor, PropertyDefDescriptor +{ + + private String fieldName; + private String jcrName; + private String elementClassName; + private String jcrElementName; + private String collectionConverterClassName; + private String collectionClassName; + private boolean proxy; + private boolean autoRetrieve = true; + private boolean autoUpdate = true; + private boolean autoInsert = true; + private String jcrType; + private boolean jcrAutoCreated; + private boolean jcrMandatory; + private String jcrOnParentVersion; + private boolean jcrProtected; + private boolean jcrSameNameSiblings; + private boolean jcrMultiple; + private String defaultPrimaryType; + + private ClassDescriptor classDescriptor; + + public String getFieldName() + { + return fieldName; + } + + public void setFieldName(String fieldName) + { + this.fieldName = fieldName; + } + + public String getJcrName() + { + return jcrName; + } + + public void setJcrName(String jcrName) + { + this.jcrName = jcrName; + } + + public String getElementClassName() + { + return elementClassName; + } + + public void setElementClassName(String elementClassName) + { + this.elementClassName = elementClassName; + } + + public String getJcrElementName() + { + return jcrElementName; + } + + public void setJcrElementName(String jcrElementName) + { + this.jcrElementName = jcrElementName; + } + + + public boolean isProxy() + { + return proxy; + } + + public void setProxy(boolean proxy) + { + this.proxy = proxy; + } + + + + public boolean isAutoInsert() { + return autoInsert; + } + public void setAutoInsert(boolean autoInsert) { + this.autoInsert = autoInsert; + } + public boolean isAutoRetrieve() { + return autoRetrieve; + } + public void setAutoRetrieve(boolean autoRetrieve) { + this.autoRetrieve = autoRetrieve; + } + public boolean isAutoUpdate() { + return autoUpdate; + } + public void setAutoUpdate(boolean autoUpdate) { + this.autoUpdate = autoUpdate; + } + + public String getCollectionConverter() + { + return collectionConverterClassName; + } + + public void setCollectionConverter(String collectionConverterClassName) + { + this.collectionConverterClassName = collectionConverterClassName; + } + + /** + * + * @return the collection class name (can be also a Map) + */ + public String getCollectionClassName() + { + return collectionClassName; + } + + /** + * Set the collection class name. + * This collection class has to implement {@link org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection} + * @param collectionClassName The collection class name to set + */ + public void setCollectionClassName(String collectionClassName) + { + this.collectionClassName = collectionClassName; + } + + /** + * + * @return The associated class descriptor + */ + public ClassDescriptor getClassDescriptor() + { + return classDescriptor; + } + + /** + * Set the associated class descriptor + * @param classDescriptor the class descriptor to set + */ + public void setClassDescriptor(ClassDescriptor classDescriptor) + { + this.classDescriptor = classDescriptor; + } + + + public String getJcrType() { + return jcrType; + } + + public void setJcrType(String value) { + this.jcrType = value; + } + + public boolean isJcrAutoCreated() + { + return jcrAutoCreated; + } + + public void setJcrAutoCreated(boolean value) + { + this.jcrAutoCreated = value; + } + + public boolean isJcrMandatory() + { + return jcrMandatory; + } + + public void setJcrMandatory(boolean value) + { + this.jcrMandatory = value; + } + + public String getJcrOnParentVersion() + { + return jcrOnParentVersion; + } + + public void setJcrOnParentVersion(String value) + { + this.jcrOnParentVersion = value; + } + + public boolean isJcrProtected() + { + return jcrProtected; + } + + public void setJcrProtected(boolean value) + { + this.jcrProtected = value; + } + + public boolean isJcrSameNameSiblings() + { + return jcrSameNameSiblings; + } + + public void setJcrSameNameSiblings(boolean value) + { + this.jcrSameNameSiblings = value; + } + + public boolean isJcrMultiple() { + return jcrMultiple; + } + + public void setJcrMultiple(boolean value) { + this.jcrMultiple = value; + } + + public String toString() { + + return "Collection Descriptor : " + this.getFieldName(); + } + + public String getDefaultPrimaryType() { + return defaultPrimaryType; + } + + public void setDefaultPrimaryType(String defaultPrimaryType) { + this.defaultPrimaryType = defaultPrimaryType; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/FieldDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/FieldDescriptor.java new file mode 100644 index 00000000..382d8cd9 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/FieldDescriptor.java @@ -0,0 +1,279 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + + + +/** + * + * + * FieldDescriptor is used by the mapper to read general information on a atomic field + * + * @author Lombart Christophe + * + */ +public class FieldDescriptor implements PropertyDefDescriptor { + private String fieldName; + private String jcrName; + private String jcrType; + private boolean jcrAutoCreated; + private boolean jcrMandatory; + private String jcrOnParentVersion; + private boolean jcrProtected; + private boolean jcrMultiple; + private ClassDescriptor classDescriptor; + private boolean id; + private boolean path; + private boolean uuid; + private String converter; + private String jcrDefaultValue; + private String[] jcrValueConstraints = new String[0]; + + + /** + * @return Returns the fieldName. + */ + public String getFieldName() { + return fieldName; + } + + /** + * @param fieldName The fieldName to set. + */ + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + + /** + * @return Returns the jcrName. + */ + public String getJcrName() { + return jcrName; + } + + /** + * @param jcrName The jcrName to set. + */ + public void setJcrName(String jcrName) { + this.jcrName = jcrName; + } + + + /** + * + * @return The atomic type converter to use, can be null + */ + public String getConverter() { + return converter; + } + + /** + * Set the atomic converter + * @param converter the atomic converter to use + */ + public void setConverter(String converter) { + this.converter = converter; + } + + /** + * + * @return the associated class descriptor + */ + public ClassDescriptor getClassDescriptor() { + return classDescriptor; + } + + /** + * Set the associated class descriptor + * @param classDescriptor the class descriptor to set + */ + public void setClassDescriptor(ClassDescriptor classDescriptor) { + this.classDescriptor = classDescriptor; + } + + /** + * @return true if the field is the class ID + */ + public boolean isId() { + return id; + } + + /** + * + * @param id + */ + public void setId(boolean id) { + this.id = id; + } + + /** + * @return Returns true if the field is the object JCR path. + */ + public boolean isPath() { + return path; + } + + /** + * @param path The path to set. + */ + public void setPath(boolean path) { + this.path = path; + } + + /** + * @return Returns true if the field is the UUID. + */ + public boolean isUuid() { + return uuid; + } + + /** + * @param path The path to set. + */ + public void setUuid(boolean uuid) { + this.uuid = uuid; + } + + /** Getter for property jcrType. + * + * @return jcrType + */ + public String getJcrType() { + return jcrType; + } + + /** Setter for property jcrType. + * + * @param value jcrType + */ + public void setJcrType(String value) { + this.jcrType = value; + } + + /** Getter for propery jcrAutoCreated. + * + * @return jcrAutoCreated + */ + public boolean isJcrAutoCreated() { + return jcrAutoCreated; + } + + /** Setter for property jcrAutoCreated. + * + * @param value jcrAutoCreated + */ + public void setJcrAutoCreated(boolean value) { + this.jcrAutoCreated = value; + } + + /** Getter for property jcrMandatory. + * + * @return jcrMandatory + */ + public boolean isJcrMandatory() { + return jcrMandatory; + } + + /** Setter for property jcrMandatory. + * + * @param value jcrMandatory + */ + public void setJcrMandatory(boolean value) { + this.jcrMandatory = value; + } + + /** Getter for property jcrOnParentVersion. + * + * @return jcrOnParentVersion + */ + public String getJcrOnParentVersion() { + return jcrOnParentVersion; + } + + /** Setter for property jcrOnParentVersion. + * + * @param value jcrOnParentVersion + */ + public void setJcrOnParentVersion(String value) { + this.jcrOnParentVersion = value; + } + + /** Getter for property jcrProtected. + * + * @return jcrProtected + */ + public boolean isJcrProtected() { + return jcrProtected; + } + + /** Setter for property jcrProtected. + * + * @param value jcrProtected + */ + public void setJcrProtected(boolean value) { + this.jcrProtected = value; + } + + /** Getter for property jcrMultiple. + * + * @return jcrMultiple + */ + public boolean isJcrMultiple() { + return jcrMultiple; + } + + /** Setter for property jcrMultiple. + * + * @param value jcrMultiple + */ + public void setJcrMultiple(boolean value) { + this.jcrMultiple = value; + } + + public String getJcrDefaultValue() { + return jcrDefaultValue; + } + + public void setJcrDefaultValue(String defaultValue) { + this.jcrDefaultValue = defaultValue; + } + + public String[] getJcrValueConstraints() { + return jcrValueConstraints; + } + + public void setJcrValueConstraints(String[] jcrValueConstraints) { + if (null != jcrValueConstraints && jcrValueConstraints.length == 1) { + this.jcrValueConstraints = jcrValueConstraints[0].split(" *, *"); + } + + } + + public void setJcrValueConstraints(String jcrValueConstraints) { + if (jcrValueConstraints != null && ! jcrValueConstraints.equals("")) + { + this.jcrValueConstraints = jcrValueConstraints.split(" *, *"); + } + } + + + public String toString() { + + return "Field Descriptor : " + this.getFieldName(); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ImplementDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ImplementDescriptor.java new file mode 100644 index 00000000..3e866a94 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/ImplementDescriptor.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + + +/** + * + * + * ImplementDescriptor is used by the mapper to read general information on a implemented interface + * + * @author Lombart Christophe + * + */ +public class ImplementDescriptor { + private String interfaceName; + + public String getInterfaceName() { + return interfaceName; + } + + public void setInterfaceName(String interfaceName) { + this.interfaceName = interfaceName; + } + + public String toString() { + + return "Implement Descriptor : " + this.interfaceName; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/MappingDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/MappingDescriptor.java new file mode 100644 index 00000000..ee9d809c --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/MappingDescriptor.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.apache.jackrabbit.ocm.manager.ManagerConstant; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * MappingDescriptor is an helper class used to access to the {@link ClassDescriptor} + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +public class MappingDescriptor { + + private static Logger log = LoggerFactory.getLogger(MappingDescriptor.class); + private HashMap classDescriptorsByClassName = new HashMap(); + private HashMap classDescriptorsByNodeType = new HashMap(); + + private Mapper mapper; + + private String packageName; + + public void setPackage(String pckgName) { + this.packageName = pckgName; + } + + + /** + * Add a new ClassDescriptor + * + * @param classDescriptor The class descriptor to add + */ + public void addClassDescriptor(ClassDescriptor classDescriptor) { + + + if (classDescriptorsByClassName.get(classDescriptor.getClassName()) != null) + { + log.warn("Duplicate classdescriptor for : " + classDescriptor.getClassName() + ". The mapping setting will be overriden"); + } + + log.debug("Adding the class descriptor for : {}", classDescriptor.getClassName()); + if (null != this.packageName && !"".equals(this.packageName)) { + classDescriptor.setClassName(this.packageName + "." + classDescriptor.getClassName()); + + if (null != classDescriptor.getExtend() && !"".equals(classDescriptor.getExtend())) { + classDescriptor.setExtend(this.packageName + "." + classDescriptor.getExtend()); + } + } + + classDescriptorsByClassName.put(classDescriptor.getClassName(), classDescriptor); + + if (null != classDescriptor.getJcrType() && ! "".equals(classDescriptor.getJcrType()) && + ! ManagerConstant.NT_UNSTRUCTURED.equals(classDescriptor.getJcrType())) + { + if ((classDescriptorsByNodeType.get(classDescriptor.getJcrType()) != null) && + classDescriptor.usesNodeTypePerConcreteClassStrategy() ) + { + log.warn("Duplicate classdescriptor for node type : " + classDescriptor.getJcrType()); + } + classDescriptorsByNodeType.put(classDescriptor.getJcrType(), classDescriptor); + } + classDescriptor.setMappingDescriptor(this); + } + + /** + * Get the classdescriptor to used for the class + * @param className the class name + * @return the class descriptor found or null + */ + public ClassDescriptor getClassDescriptorByName(String className) { + return (ClassDescriptor) classDescriptorsByClassName.get(className); + } + + public ClassDescriptor getClassDescriptorByNodeType(String nodeType) + { + return (ClassDescriptor) classDescriptorsByNodeType.get(nodeType); + } + + public Collection getAllClassDescriptors() + { + return classDescriptorsByClassName.values(); + } + + /** + * Get all class descriptors by class name + * @return all class descriptors found + */ + public Map getClassDescriptorsByClassName() { + return classDescriptorsByClassName; + } + /** + * Get all class descriptors by class name + * @return all class descriptors found + */ + public Map getClassDescriptorsByNodeType() { + return classDescriptorsByNodeType; + } + public Mapper getMapper() { + return this.mapper; + } + + public void setMapper(Mapper parentMapper) { + this.mapper = parentMapper; + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/mapper/model/PropertyDefDescriptor.java b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/PropertyDefDescriptor.java new file mode 100755 index 00000000..f7cb8ca6 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/mapper/model/PropertyDefDescriptor.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper.model; + +/** + * PropertyDefDescriptor is used by the node type management tools based on + * class descriptors to manage property definitions + * + * @author Felix Meschberger + */ +public interface PropertyDefDescriptor { + + /** + * @return Returns the name of the property. + */ + String getJcrName(); + + String getFieldName(); + + /** + * @return Returns the property type name. + */ + String getJcrType(); + + /** + * @return Whether the property is auto created. + */ + boolean isJcrAutoCreated(); + + /** + * @return Whether the property is mandatory. + */ + boolean isJcrMandatory(); + + /** + * @return What to do on parent version creation. + */ + String getJcrOnParentVersion(); + + /** + * @return Whether the property is protected. + */ + boolean isJcrProtected(); + + /** + * @return Whether the property is multi-valued. + */ + boolean isJcrMultiple(); +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/NodeTypeManager.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/NodeTypeManager.java new file mode 100644 index 00000000..0e111456 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/NodeTypeManager.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement; + +import java.io.InputStream; +import java.util.List; + +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.MappingDescriptor; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NamespaceCreationException; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NodeTypeCreationException; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NodeTypeRemovalException; +import org.apache.jackrabbit.ocm.nodemanagement.exception.OperationNotSupportedException; + + +/** This interface defines the API for JCR Node Type Management implementations. + * It does not contain any JCR vendor specific methods. + * + * Classes that implement this interface are used to create custom node types in + * a JCR repository. Each JCR repository has its own way of doing this as it is + * not defined by the JSR-170 spec. The default implementation of jcr-nodemanagement is Jackrabbit. + * + * In order to create JCR custom node types you need to provide an established + * session to a JCR repository. The user that is logged into has to have the + * necessary permissions to create nodes (user has to have "superuser" rights). + * + * The JCR Node Type Management tools are an extension to the jcr-mapping + * tools. NodeTypeManager implementations depend on the jcr-mapping + * xml file and the object model defined by jcr-mapping. + * + * @author Oliver Kiessler + */ +public interface NodeTypeManager { + + /** Creates a new namespace in the repository. + * + * @param namespace Namespace + * @param namespaceUri Full namespace URI + */ + void createNamespace(Session session, String namespace, String namespaceUri) + throws NamespaceCreationException; + + /** This method creates JCR node types based on the MappingDescriptor object + * which is created by a jcr-mapping Mapper implementation. A + * Mapper reads one to many jcr mapping XML File. + * + * @param session Repository session + * @param mappingDescriptor Mapping descriptor object created by + * jcr-mapping + * @throws NodeTypeCreationException NodeTypeCreationException + */ + void createNodeTypes(Session session, MappingDescriptor mappingDescriptor) + throws NodeTypeCreationException; + + /** This method creates JCR node types based on ClassDescriptor objects + * which are created by a jcr-mapping Mapper implementation. A + * Mapper reads one to many jcr mapping XML File. + * + * @param session Repository session + * @param classDescriptors Array of ClassDescriptor objects created by + * jcr-mapping + * @throws NodeTypeCreationException NodeTypeCreationException + */ + void createNodeTypes(Session session, ClassDescriptor[] classDescriptors) + throws NodeTypeCreationException; + + /** This method creates a single JCR node type identified by its ClassDescriptor + * read from the jcr mapping file. + * + * @param session Repository session + * @param classDescriptor ClassDescriptor object created by jcr-mapping + * @throws NodeTypeCreationException NodeTypeCreationException + */ + void createSingleNodeType(Session session, ClassDescriptor classDescriptor) + throws NodeTypeCreationException; + + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/BaseNodeManagementException.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/BaseNodeManagementException.java new file mode 100644 index 00000000..c3b14cb8 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/BaseNodeManagementException.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.exception; + +import java.io.PrintStream; +import java.io.PrintWriter; + +/** Base exception for all JCR Node Type Management exceptions. + * + * @author Oliver Kiessler + */ +public class BaseNodeManagementException extends Exception +{ + + /** Root exception. + */ + private Exception wrappedException; + + /** Creates a new instance of BaseNodeManagementException. */ + public BaseNodeManagementException() + { + } + + /** Creates a new instance of BaseNodeManagementException. + * @param message Exception message + */ + public BaseNodeManagementException(String message) + { + super(message); + } + + /** Creates a new instance of BaseNodeManagementException. + * @param rootException Root Exception + */ + public BaseNodeManagementException(Exception rootException) + { + setWrappedException(rootException); + } + + /** Getter for property wrappedException. + * + * @return wrappedException + */ + public Exception getWrappedException() + { + return wrappedException; + } + + /** Setter for property wrappedException. + * + * @param object wrappedException + */ + public void setWrappedException(Exception object) + { + this.wrappedException = object; + } + + public void printStackTrace( PrintStream ps ) + { + if ( getWrappedException() == null || getWrappedException() == this ) + { + super.printStackTrace( ps ); + } + else + { + ps.println( this ); + getWrappedException().printStackTrace( ps ); + } + } + + public void printStackTrace( PrintWriter pw ) + { + if ( getWrappedException() == null || getWrappedException() == this ) + { + super.printStackTrace( pw ); + } + else + { + pw.println( this ); + getWrappedException().printStackTrace( pw ); + } + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NamespaceCreationException.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NamespaceCreationException.java new file mode 100644 index 00000000..9fe45887 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NamespaceCreationException.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.exception; + +/** Exception that is thrown when a JCR namespace could not be created. + * + * @author Oliver Kiessler + */ +public class NamespaceCreationException extends BaseNodeManagementException +{ + + /** Creates a new instance of NamespaceCreationException. */ + public NamespaceCreationException() + { + } + + /** Creates a new instance of NamespaceCreationException. + * @param wrappedException Root exception + */ + public NamespaceCreationException(Exception wrappedException) + { + setWrappedException(wrappedException); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NodeTypeCreationException.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NodeTypeCreationException.java new file mode 100644 index 00000000..86ceb555 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NodeTypeCreationException.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.exception; + +/** Exception that is thrown when a JCR node type could not be created. + * + * @author Oliver Kiessler + */ +public class NodeTypeCreationException extends BaseNodeManagementException +{ + + /** Creates a new instance of NodeTypeCreationException. */ + public NodeTypeCreationException() + { + } + + /** Creates a new instance of NodeTypeCreationException. */ + public NodeTypeCreationException(String message) + { + super(message); + } + + /** Creates a new instance of NodeTypeCreationException. + * @param wrappedException Root exception + */ + public NodeTypeCreationException(Exception wrappedException) + { + setWrappedException(wrappedException); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NodeTypeRemovalException.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NodeTypeRemovalException.java new file mode 100644 index 00000000..1a222b67 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/NodeTypeRemovalException.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.exception; + +/** Exception that is thrown when a JCR node type could not be removed. + * + * @author Oliver Kiessler + */ +public class NodeTypeRemovalException extends BaseNodeManagementException +{ + + /** Creates a new instance of NodeTypeRemovalException. */ + public NodeTypeRemovalException() + { + } + + /** Creates a new instance of NodeTypeRemovalException. + * @param wrappedException Root exception + */ + public NodeTypeRemovalException(Exception wrappedException) + { + setWrappedException(wrappedException); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/OperationNotSupportedException.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/OperationNotSupportedException.java new file mode 100644 index 00000000..ee5e4fde --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/exception/OperationNotSupportedException.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.exception; + +/** Exception that is thrown if a JCR operation is not supported by + * a JCR repository implementation. + * + * @author Oliver Kiessler + */ +public class OperationNotSupportedException extends BaseNodeManagementException +{ + + /** Creates a new instance of NodeTypeRemovalException. */ + public OperationNotSupportedException() + { + } + + /** Creates a new instance of NodeTypeRemovalException. + * @param wrappedException Root exception + */ + public OperationNotSupportedException(Exception wrappedException) + { + setWrappedException(wrappedException); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/impl/NodeTypeManagerImpl.java b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/impl/NodeTypeManagerImpl.java new file mode 100644 index 00000000..c7f20cd0 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/nodemanagement/impl/NodeTypeManagerImpl.java @@ -0,0 +1,328 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.impl; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.Value; +import javax.jcr.ValueFactory; +import javax.jcr.nodetype.NodeDefinitionTemplate; +import javax.jcr.nodetype.NodeTypeTemplate; +import javax.jcr.nodetype.PropertyDefinitionTemplate; +import javax.jcr.version.OnParentVersionAction; + +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ChildNodeDefDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.MappingDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.PropertyDefDescriptor; +import org.apache.jackrabbit.ocm.nodemanagement.NodeTypeManager; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NamespaceCreationException; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NodeTypeCreationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NodeTypeManagerImpl implements NodeTypeManager { + + private static Logger log = LoggerFactory.getLogger(NodeTypeManagerImpl.class); + @Override + public void createNamespace(final Session session, final String namespace, final String namespaceUri) throws NamespaceCreationException { + if (session != null) + { + try + { + session.getWorkspace().getNamespaceRegistry().registerNamespace(namespace, namespaceUri); + log.info("Namespace created: " + + "{" + namespaceUri + "}" + namespace); + } + catch (Exception e) + { + throw new NamespaceCreationException(e); + } + } + } + + @Override + public void createNodeTypes(final Session session, final MappingDescriptor mappingDescriptor) throws NodeTypeCreationException { + if (mappingDescriptor != null && mappingDescriptor.getClassDescriptorsByClassName().size() > 0) + { + final Collection classDescriptorObjects = mappingDescriptor.getClassDescriptorsByClassName().values(); + final ClassDescriptor[] classDescriptors = (ClassDescriptor[])classDescriptorObjects.toArray(new ClassDescriptor[classDescriptorObjects.size()]); + createNodeTypes(session, classDescriptors); + } + else + { + throw new NodeTypeCreationException("The MappingDescriptor can't be null or empty."); + } + } + + @Override + public void createNodeTypes(final Session session, final ClassDescriptor[] classDescriptors) throws NodeTypeCreationException { + if (classDescriptors != null && classDescriptors.length > 0) + { + log.info("Trying to create " + classDescriptors.length + + " JCR node types."); + for (int i = 0; i < classDescriptors.length; i++) + { + createSingleNodeType(session, classDescriptors[i]); + } + } + else + { + throw new NodeTypeCreationException("The ClassDescriptor can't be null or empty."); + } + } + + @Override + public void createSingleNodeType(final Session session, final ClassDescriptor classDescriptor) throws NodeTypeCreationException { + try { + if (classDescriptor.getJcrType() != null && + (classDescriptor.getJcrType().startsWith("nt:") + || classDescriptor.getJcrType().startsWith("mix:"))) { + throw new NodeTypeCreationException("Namespace nt and mix are reserved namespaces. Please specify your own."); + } + + if (checkSuperTypes(session.getWorkspace().getNodeTypeManager(), + classDescriptor.getJcrSuperTypes())) { + + javax.jcr.nodetype.NodeTypeManager ntm = session.getWorkspace().getNodeTypeManager(); + final NodeTypeTemplate ntt = ntm.createNodeTypeTemplate(); + + if (classDescriptor.getJcrType() == null) { + ntt.setName(classDescriptor.getClassName()); + } else { + ntt.setName(classDescriptor.getJcrType()); + } + ntt.setAbstract(classDescriptor.isAbstract()); + if (classDescriptor.getJcrSuperTypes() != null && classDescriptor.getJcrSuperTypes().length() > 0) { + String[] superTypesArray = classDescriptor.getJcrSuperTypes().split(","); + //TODO combine the mixins here as well as supertypes + // Add classDescriptor.getJcrMixinTypes() to superTypesArray + for (String s : classDescriptor.getJcrMixinTypes()) { + System.out.println(s); + } + ntt.setDeclaredSuperTypeNames(superTypesArray); + } + // should we also support mixins to be created? + ntt.setMixin(false); + ntt.setQueryable(true); + ntt.setOrderableChildNodes(true); + + final List nodeDefinitionTemplates = ntt.getNodeDefinitionTemplates(); + final List propertyDefinitionTemplates = ntt.getPropertyDefinitionTemplates(); + + if (classDescriptor.getFieldDescriptors() != null) { + Iterator fieldIterator = classDescriptor.getFieldDescriptors().iterator(); + while (fieldIterator.hasNext()) { + FieldDescriptor field = (FieldDescriptor) fieldIterator.next(); + if (!field.isPath()) { + final PropertyDefinitionTemplate pdt = getPropertyDefinition(ntm, session.getValueFactory(), field); + // add the just created pdt to the nodetypetemplate + propertyDefinitionTemplates.add(pdt); + } + } + + if (classDescriptor.getBeanDescriptors() != null) { + Iterator beanIterator = classDescriptor.getBeanDescriptors().iterator(); + while (beanIterator.hasNext()) { + BeanDescriptor field = (BeanDescriptor) beanIterator.next(); + if (this.isPropertyType(field.getJcrType())) { + final PropertyDefinitionTemplate pdt = getPropertyDefinition(ntm, session.getValueFactory(), field); + // add the just created pdt to the nodetypetemplate + propertyDefinitionTemplates.add(pdt); + } else { + final NodeDefinitionTemplate ndt = getNodeDefinition(ntm, session.getValueFactory(), field); + // add the just created pdt to the nodetypetemplate + nodeDefinitionTemplates.add(ndt); + } + } + } + + if (classDescriptor.getCollectionDescriptors() != null) { + Iterator collectionIterator = classDescriptor.getCollectionDescriptors().iterator(); + while (collectionIterator.hasNext()) { + CollectionDescriptor field = (CollectionDescriptor) collectionIterator.next(); + if (this.isPropertyType(field.getJcrType())) { + final PropertyDefinitionTemplate pdt = getPropertyDefinition(ntm, session.getValueFactory(), field); + // add the just created pdt to the nodetypetemplate + propertyDefinitionTemplates.add(pdt); + } else { + final NodeDefinitionTemplate ndt = getNodeDefinition(ntm, session.getValueFactory(), field); + // add the just created pdt to the nodetypetemplate + nodeDefinitionTemplates.add(ndt); + } + } + } + ntm.registerNodeType(ntt, false); + log.info("Registered JCR node type '" + ntt.getName() + + "' for class '" + classDescriptor.getClassName() + "'"); + } + } else { + throw new NodeTypeCreationException("JCR supertypes could not be resolved."); + } + } catch (Exception e) { + log.error("Could not create node types from class descriptor.", e); + throw new NodeTypeCreationException(e); + } + } + + private NodeDefinitionTemplate getNodeDefinition(final javax.jcr.nodetype.NodeTypeManager ntm, + final ValueFactory valueFactory, + final ChildNodeDefDescriptor field) throws RepositoryException { + + + final NodeDefinitionTemplate ndt = ntm.createNodeDefinitionTemplate(); + if (field.getJcrName() != null) { + ndt.setName(field.getJcrName()); + } else { + ndt.setName("*"); + } + + int onParentVersion = OnParentVersionAction.IGNORE; + + if (field.getJcrOnParentVersion() != null + && field.getJcrOnParentVersion().length() > 0) { + onParentVersion = OnParentVersionAction.valueFromName(field.getJcrOnParentVersion()); + } + ndt.setOnParentVersion(onParentVersion); + ndt.setSameNameSiblings(field.isJcrSameNameSiblings()); + + ndt.setAutoCreated(field.isJcrAutoCreated()); + ndt.setDefaultPrimaryTypeName(field.getDefaultPrimaryType()); + ndt.setMandatory(field.isJcrMandatory()); + ndt.setProtected(field.isJcrProtected()); + ndt.setRequiredPrimaryTypeNames(getJcrSuperTypes(field.getJcrType())); + + return ndt; + } + + private PropertyDefinitionTemplate getPropertyDefinition(final javax.jcr.nodetype.NodeTypeManager ntm, + final ValueFactory valueFactory, + final PropertyDefDescriptor field) throws RepositoryException { + final PropertyDefinitionTemplate pdt = ntm.createPropertyDefinitionTemplate(); + if (field.getJcrName() != null) { + pdt.setName(field.getJcrName()); + } else { + pdt.setName(field.getFieldName()); + } + + if (field.getJcrType() != null) { + try { + pdt.setRequiredType(PropertyType.valueFromName(field.getJcrType())); + } catch (IllegalArgumentException e) { + log.warn("Invalid property type '{}' for '{}'. Set default to String type", field.getJcrType(), field.getJcrName()); + pdt.setRequiredType(PropertyType.STRING); + } + } else { + log.info("No property type set for {}. Setting 'String' type.", field.getJcrName()); + pdt.setRequiredType(PropertyType.STRING); + + } + int onParentVersion = OnParentVersionAction.IGNORE; + if (field.getJcrOnParentVersion() != null && + field.getJcrOnParentVersion().length() > 0) { + onParentVersion = OnParentVersionAction.valueFromName(field.getJcrOnParentVersion()); + } + pdt.setOnParentVersion(onParentVersion); + + pdt.setAutoCreated(field.isJcrAutoCreated()); + pdt.setAvailableQueryOperators(new String[0]); + + pdt.setFullTextSearchable(true); + pdt.setMandatory(field.isJcrMandatory()); + pdt.setMultiple(field.isJcrMultiple()); + pdt.setOnParentVersion(onParentVersion); + pdt.setProtected(field.isJcrProtected()); + pdt.setQueryOrderable(true); + + if (field instanceof FieldDescriptor) { + FieldDescriptor f = (FieldDescriptor) field; + if (f.getJcrDefaultValue() != null) { + if (pdt.getRequiredType() == PropertyType.STRING) { + Value[] vals = {valueFactory.createValue(f.getJcrDefaultValue())}; + pdt.setDefaultValues(vals); + } else { + log.warn("Can only set default value for String properties. Skip for field '{}'", field.getJcrName()); + } + } + pdt.setValueConstraints(f.getJcrValueConstraints()); + } + + return pdt; + } + + /** Checks if all JCR super types for a given node type exist. + * + * @param ntMgr NodeTypeManager + * @param superTypes Comma separated String with JCR node types + * @return returns false if one of the supertypes does not exist, otherwise returns true + */ + private boolean checkSuperTypes(javax.jcr.nodetype.NodeTypeManager ntMgr, + String superTypes) + { + boolean exists = true; + + if (superTypes != null && superTypes.length() > 0) + { + String[] superTypesArray = superTypes.split(","); + log.debug("JCR super types found: {}", superTypesArray.length); + for (int i = 0; i < superTypesArray.length; i++) + { + try + { + ntMgr.getNodeType(superTypesArray[i]); + } + catch (Exception e) + { + log.error("JCR super type '" + superTypesArray[i] + "' does not exist!"); + exists = false; + break; + } + } + } + + return exists; + } + + public String[] getJcrSuperTypes(String superTypes) + { + return superTypes.split(","); + } + + private boolean isPropertyType(String type) + { + return (type.equals(PropertyType.TYPENAME_BINARY) || + type.equals(PropertyType.TYPENAME_BOOLEAN) || + type.equals(PropertyType.TYPENAME_DATE) || + type.equals(PropertyType.TYPENAME_DOUBLE) || + type.equals(PropertyType.TYPENAME_LONG) || + type.equals(PropertyType.TYPENAME_NAME) || + type.equals(PropertyType.TYPENAME_PATH) || + type.equals(PropertyType.TYPENAME_REFERENCE) || + type.equals(PropertyType.TYPENAME_WEAKREFERENCE) || + type.equals(PropertyType.TYPENAME_DECIMAL) || + type.equals(PropertyType.TYPENAME_URI) || + type.equals(PropertyType.TYPENAME_STRING)); + } +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/query/Filter.java b/src/main/java/org/apache/jackrabbit/ocm/query/Filter.java new file mode 100644 index 00000000..a46cbe81 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/query/Filter.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.query; + + +/** + * + * JCR Filter interface. + * + * @author Christophe Lombart + * + */ +public interface Filter +{ + /** + * Set the filter scope. The scope is an Node path specifying where to search in the content tree. + * For example, + * /mynode/mysecondnode/', the search engine will search on child objects in the /mynode/mysecondnode + * /mynode/mysecondnode//', the search engine will search on desncendant objects in the /mynode/mysecondnode (the complete subnode tree) + * + * @param scope The filter scope + * + */ + void setScope(String scope); + + + /** + * Get the filter scope. + * + * @return The filter scope + */ + String getScope(); + + + /** + * Set the node name used to build the jcr search expression. + * + * @param nodeName + */ + void setNodeName(String nodeName); + + /** + * Get the node name used in the jcr expression + * @return + */ + String getNodeName(); + + + /** + * Search content based on a fullTextSearch. + * Depending on the full text search engine, you can also filter on properties. + * + * @param scope either a a jcr node or propserty. If a node is used, all properties of this node are searche (following the internal index + * @param fullTextSearch The full text search string + */ + Filter addContains(String scope, String fullTextSearch); + + Filter addBetween(String arg0, Object arg1, Object arg2); + + Filter addEqualTo(String arg0, Object arg1); + + Filter addGreaterOrEqualThan(String arg0, Object arg1); + + Filter addGreaterThan(String arg0, Object arg1); + + Filter addLessOrEqualThan(String arg0, Object arg1); + + Filter addLessThan(String arg0, Object arg1); + + Filter addLike(String arg0, Object arg1); + + Filter addNotEqualTo(String arg0, Object arg1); + + Filter addNotNull(String arg0); + + Filter addIsNull(String arg0); + + Filter addOrFilter(String fieldAttributeName, String[] valueList); + + Filter addOrFilter(Filter arg0); + + Filter addAndFilter(Filter filter); + + Filter addJCRExpression(String jcrExpression); + + Class getFilterClass(); + Object clone(); + + +} diff --git a/src/java/org/apache/portals/graffito/jcr/query/Query.java b/src/main/java/org/apache/jackrabbit/ocm/query/Query.java similarity index 62% rename from src/java/org/apache/portals/graffito/jcr/query/Query.java rename to src/main/java/org/apache/jackrabbit/ocm/query/Query.java index 004ec6ad..211a1051 100644 --- a/src/java/org/apache/portals/graffito/jcr/query/Query.java +++ b/src/main/java/org/apache/jackrabbit/ocm/query/Query.java @@ -1,10 +1,10 @@ /* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -15,11 +15,11 @@ * limitations under the License. */ -package org.apache.portals.graffito.jcr.query; +package org.apache.jackrabbit.ocm.query; /** - * Graffito JCR Query interface - * + * JCR Query interface + * * @author Christophe Lombart * */ @@ -27,25 +27,25 @@ public interface Query { /** - * Set the filter to use with this query + * Set the filter to use with this query * @param filter The filter to use */ public void setFilter(Filter filter); /** - * + * * @return The filter used for this query */ public Filter getFilter(); /** - * Order the object found (ascending) + * Order the object found (ascending) * @param fieldNameAttribute the name of the field used to sort the search result */ public void addOrderByAscending(String fieldNameAttribute); /** - * Order the object found (descending) + * Order the object found (descending) * @param fieldNameAttribute the name of the field used to sort the search result */ diff --git a/src/java/org/apache/portals/graffito/jcr/query/QueryManager.java b/src/main/java/org/apache/jackrabbit/ocm/query/QueryManager.java similarity index 61% rename from src/java/org/apache/portals/graffito/jcr/query/QueryManager.java rename to src/main/java/org/apache/jackrabbit/ocm/query/QueryManager.java index 53780543..b1a6bf9c 100644 --- a/src/java/org/apache/portals/graffito/jcr/query/QueryManager.java +++ b/src/main/java/org/apache/jackrabbit/ocm/query/QueryManager.java @@ -1,10 +1,10 @@ /* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -15,14 +15,14 @@ * limitations under the License. */ -package org.apache.portals.graffito.jcr.query; +package org.apache.jackrabbit.ocm.query; /** - * The query manager is used to instantiate query objects and execute query based on the object model. + * The query manager is used to instantiate query objects and execute query based on the object model. * Internally, this service used the JCR QueryManager - * + * * @author Christophe Lombart * */ @@ -34,20 +34,20 @@ public interface QueryManager * @return a new instantiated filter object */ public Filter createFilter(Class classQuery); - + /** - * Create a new empty query + * Create a new empty query * @param filter the filter used by the query * @return a new instantiated query object */ - public Query createQuery(Filter filter); - + public Query createQuery(Filter filter); + /** * Build a JCR search expression from a Query * @param query the query matching to the JCR search expression - * @return a JCR XPATH search expression + * @return a JCR XPATH search expression */ - public String buildJCRExpression(Query query); - - + public String buildJCRExpression(Query query); + + } diff --git a/src/main/java/org/apache/jackrabbit/ocm/query/impl/FilterImpl.java b/src/main/java/org/apache/jackrabbit/ocm/query/impl/FilterImpl.java new file mode 100644 index 00000000..493da63e --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/query/impl/FilterImpl.java @@ -0,0 +1,360 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.query.impl; + + +import java.util.Map; + +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@link org.apache.jackrabbit.ocm.query.Filter} + * + * @author Christophe Lombart + * @author Alex Popescu + */ +public class FilterImpl implements Filter { + private final static Logger log = LoggerFactory.getLogger(FilterImpl.class); + + private Class claszz; + private String scope = ""; + private String nodeName = "*"; + private String jcrExpression = ""; + + private ClassDescriptor classDescriptor; + private Map atomicTypeConverters; + private ValueFactory valueFactory; + + /** + * Constructor + * + * @param classDescriptor + * @param atomicTypeConverters + * @param clazz + */ + public FilterImpl(ClassDescriptor classDescriptor, Map atomicTypeConverters, Class clazz, ValueFactory valueFactory) { + this.claszz = clazz; + this.atomicTypeConverters = atomicTypeConverters; + this.classDescriptor = classDescriptor; + this.valueFactory = valueFactory; + } + + public Object clone(){ + return new FilterImpl(classDescriptor,atomicTypeConverters,claszz,valueFactory); + } + /** + * + * @see org.apache.jackrabbit.ocm.query.Filter#getFilterClass() + */ + public Class getFilterClass() { + return claszz; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#setScope(java.lang.String) + */ + public void setScope(String scope) { + this.scope = scope; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#getScope() + */ + public String getScope() { + return this.scope; + } + + public String getNodeName() { + return nodeName; + } + + public void setNodeName(String nodeName) { + this.nodeName = nodeName; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addContains(java.lang.String, java.lang.String) + */ + public Filter addContains(String scope, String fullTextSearch) { + String jcrExpression = null; + if (scope.equals(".")) { + jcrExpression = "jcr:contains(., '" + fullTextSearch + "')"; + } + else { + jcrExpression = "jcr:contains(@" + this.getJcrFieldName(scope) + ", '" + fullTextSearch + + "')"; + } + + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addBetween(java.lang.String, java.lang.Object, java.lang.Object) + */ + public Filter addBetween(String fieldAttributeName, Object value1, Object value2) { + String jcrExpression = "( @" + this.getJcrFieldName(fieldAttributeName) + " >= " + + this.getStringValue(fieldAttributeName, value1) + + " and @" + this.getJcrFieldName(fieldAttributeName) + " <= " + + this.getStringValue(fieldAttributeName, value2) + ")"; + + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addEqualTo(java.lang.String, java.lang.Object) + */ + public Filter addEqualTo(String fieldAttributeName, Object value) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " = " + + this.getStringValue(fieldAttributeName, value); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addGreaterOrEqualThan(java.lang.String, java.lang.Object) + */ + public Filter addGreaterOrEqualThan(String fieldAttributeName, Object value) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " >= " + + this.getStringValue(fieldAttributeName, value); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addGreaterThan(java.lang.String, java.lang.Object) + */ + public Filter addGreaterThan(String fieldAttributeName, Object value) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " > " + + this.getStringValue(fieldAttributeName, value); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addLessOrEqualThan(java.lang.String, java.lang.Object) + */ + public Filter addLessOrEqualThan(String fieldAttributeName, Object value) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " <= " + + this.getStringValue(fieldAttributeName, value); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addLessOrEqualThan(java.lang.String, java.lang.Object) + */ + public Filter addLessThan(String fieldAttributeName, Object value) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " < " + + this.getStringValue(fieldAttributeName, value); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addLike(java.lang.String, java.lang.Object) + */ + public Filter addLike(String fieldAttributeName, Object value) { + String jcrExpression = "jcr:like(" + "@" + this.getJcrFieldName(fieldAttributeName) + ", '" + + value + "')"; + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addNotEqualTo(java.lang.String, java.lang.Object) + */ + public Filter addNotEqualTo(String fieldAttributeName, Object value) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName) + " != " + + this.getStringValue(fieldAttributeName, value); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addNotNull(java.lang.String) + */ + public Filter addNotNull(String fieldAttributeName) { + String jcrExpression = "@" + this.getJcrFieldName(fieldAttributeName); + addExpression(jcrExpression); + + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addIsNull(java.lang.String) + */ + public Filter addIsNull(String fieldAttributeName) { + String jcrExpression = "not(@" + this.getJcrFieldName(fieldAttributeName) + ")"; + addExpression(jcrExpression); + + return this; + } + + public Filter addOrFilter(String fieldAttributeName, String[] valueList) { + if (valueList==null || valueList.length==0) + return this; + final StringBuilder je = new StringBuilder(); + je.append("("); + for (Object object : valueList) { + if (je.length() > 1) + je.append(" or "); + je.append("@").append(this.getJcrFieldName(fieldAttributeName)) + .append(" = ").append(this.getStringValue(fieldAttributeName, object)); + } + je.append(")"); + addExpression(je.toString()); + return this; + } + + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addOrFilter(org.apache.jackrabbit.ocm.query.Filter) + */ + public Filter addOrFilter(Filter filter) { + FilterImpl theFilter = (FilterImpl) filter; + if (theFilter.getJcrExpression() != null && theFilter.getJcrExpression().length() > 0) + { + if ( null == jcrExpression || "".equals(jcrExpression) ) + { + jcrExpression = ((FilterImpl) filter).getJcrExpression() ; + } + else + { + jcrExpression = "(" + jcrExpression + ") or ( " + ((FilterImpl) filter).getJcrExpression() + ")"; + } + } + return this; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Filter#addAndFilter(Filter) + */ + public Filter addAndFilter(Filter filter) { + FilterImpl theFilter = (FilterImpl) filter; + if (theFilter.getJcrExpression() != null && theFilter.getJcrExpression().length() > 0) + { + if ( null == jcrExpression || "".equals(jcrExpression) ) + { + jcrExpression = ((FilterImpl) filter).getJcrExpression() ; + } + else + { + jcrExpression = "(" + jcrExpression + ") and ( " + ((FilterImpl) filter).getJcrExpression() + ")"; + } + } + return this; + } + + + public Filter addJCRExpression(String jcrExpression) { + addExpression(jcrExpression); + + return this; + } + + public Filter orJCRExpression(String jcrExpression) { + orExpression(jcrExpression); + + return this; + } + + + private String getJcrFieldName(String fieldAttribute) { + String jcrFieldName = classDescriptor.getJcrName(fieldAttribute); + if (jcrFieldName == null) { + log.error("Impossible to find the jcrFieldName for the attribute [{}] of class [{}]", + fieldAttribute, classDescriptor.getClassName(), new Exception("DIAGNOSTIC STACK TRACE")); + } + + return jcrFieldName; + + } + + private String getStringValue(String fieldName, Object value) { + FieldDescriptor fieldDescriptor = classDescriptor.getFieldDescriptor(fieldName); + AtomicTypeConverter atomicTypeConverter = null ; + // if the attribute is a simple field (primitive data type or wrapper class) + if (fieldDescriptor != null) + { + String fieldConverterName = fieldDescriptor.getConverter(); + + // if a field converter is set in the mapping, use this one + if ( fieldConverterName != null ) + { + atomicTypeConverter = (AtomicTypeConverter) ReflectionUtils.newInstance(fieldConverterName); + } + // else use a default converter in function of the attribute type + else + { + atomicTypeConverter = (AtomicTypeConverter) atomicTypeConverters.get(value.getClass()); + } + } + // else it could be a collection (for example, it is a multivalue property) + else + { + atomicTypeConverter = (AtomicTypeConverter) atomicTypeConverters.get(value.getClass()); + } + return atomicTypeConverter.getXPathQueryValue(valueFactory, value); + } + + public String getJcrExpression() { + return this.jcrExpression; + } + + private void addExpression(String jcrExpression) { + + if (this.jcrExpression.length() >0) { + this.jcrExpression += " and "; + } + this.jcrExpression += jcrExpression ; + } + + private void orExpression(String jcrExpression) { + + if (this.jcrExpression.length() >0) { + this.jcrExpression += " or "; + } + this.jcrExpression += jcrExpression ; + } + + + public String toString() { + return getJcrExpression(); + } + + +} \ No newline at end of file diff --git a/src/main/java/org/apache/jackrabbit/ocm/query/impl/QueryImpl.java b/src/main/java/org/apache/jackrabbit/ocm/query/impl/QueryImpl.java new file mode 100644 index 00000000..303deed7 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/query/impl/QueryImpl.java @@ -0,0 +1,126 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.query.impl; + +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; + +/** + * Default Query implementation + * + * @author Christophe Lombart + * + */ +public class QueryImpl implements Query +{ + + private Filter filter; + + ClassDescriptor classDescriptor; + + private final static String ORDER_BY_STRING = "order by "; + + private String jcrExpression = ""; + + /** + * Constructor + * + * @param filter + * @param mapper + */ + public QueryImpl(Filter filter, Mapper mapper) + { + this.filter = filter; + classDescriptor = mapper.getClassDescriptorByClass(filter.getFilterClass()); + } + + /** + * @see org.apache.jackrabbit.ocm.query.Query#setFilter(org.apache.jackrabbit.ocm.query.Filter) + */ + public void setFilter(Filter filter) + { + this.filter = filter; + } + + /** + * @see org.apache.jackrabbit.ocm.query.Query#getFilter() + */ + public Filter getFilter() + { + return this.filter; + } + + public void addOrderByDescending(String fieldNameAttribute) + { + //Changes made to maintain the query state updated with every addition + //@author Shrirang Edgaonkar + addExpression("@" + this.getJcrFieldName(fieldNameAttribute) + " descending"); + } + + /** + * + * @see org.apache.jackrabbit.ocm.query.Query#addOrderByAscending(java.lang.String) + */ + public void addOrderByAscending(String fieldNameAttribute) + { + addExpression("@" + this.getJcrFieldName(fieldNameAttribute) + " ascending"); + } + + public void addJCRExpression(String jcrExpression) { + addExpression(jcrExpression); + } + + + private void addExpression(String jcrExpression) { + //@author Shrirang Edgaonkar + // First time comma is not required + if(this.jcrExpression.equals("")) + { + this.jcrExpression += jcrExpression ; + }else + this.jcrExpression += (" , " + jcrExpression) ; + } + + + + public String getOrderByExpression() + { + if(jcrExpression.equals("")) + return ""; + else + { + //@author Shrirang Edgaonkar + //Ensure that the OrderBy string is added only once + if(this.jcrExpression.contains(ORDER_BY_STRING)) + return this.jcrExpression; + else + return (ORDER_BY_STRING + this.jcrExpression); + } + } + + + private String getJcrFieldName(String fieldAttribute) + { + + return classDescriptor.getJcrName(fieldAttribute); + + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/query/impl/QueryManagerImpl.java b/src/main/java/org/apache/jackrabbit/ocm/query/impl/QueryManagerImpl.java new file mode 100644 index 00000000..8259eb62 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/query/impl/QueryManagerImpl.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.query.impl; + + +import java.util.Iterator; +import java.util.Map; + +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.manager.ManagerConstant; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class QueryManagerImpl implements QueryManager { + + private final static Logger log = LoggerFactory.getLogger(ObjectContentManagerImpl.class); + + private Mapper mapper; + private Map atomicTypeConverters; + private ValueFactory valueFactory; + + public QueryManagerImpl(Mapper mapper, Map atomicTypeConverters, ValueFactory valueFactory) { + this.mapper = mapper; + this.atomicTypeConverters = atomicTypeConverters; + this.valueFactory = valueFactory; + } + + public Filter createFilter(Class classQuery) { + return new FilterImpl(mapper.getClassDescriptorByClass(classQuery), + atomicTypeConverters, + classQuery, valueFactory); + } + + public Query createQuery(Filter filter) { + return new QueryImpl(filter, mapper); + } + + public String buildJCRExpression(Query query) { + + Filter filter = query.getFilter(); + + // Check if the class has an inheritance discriminator field + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(filter.getFilterClass()); + if (classDescriptor.hasDiscriminator()) { + Filter discrininatorFilter = buildDiscriminatorFilter(query, classDescriptor); + filter = filter.addAndFilter(discrininatorFilter); + } + + String jcrExp = ""; + + // Add scope & node name + if (((filter.getScope() != null) && (!filter.getScope().equals("")))) { + jcrExp += "/jcr:root" + filter.getScope() + "element(" + filter.getNodeName() + ", "; + } + else { + jcrExp += "//element(" + filter.getNodeName() + ", "; + } + + // Add node type + jcrExp += this.getNodeType(filter) + ") "; + + // Add filter criteria + String filterExp = ((FilterImpl) filter).getJcrExpression(); + + // Build the jcr filter + if ((filterExp != null) && (!filterExp.equals(""))) { + jcrExp += "[" + filterExp + "]"; + } + + // Add order by + jcrExp += ((QueryImpl) query).getOrderByExpression(); + log.debug(jcrExp); + + return jcrExp; + + } + + private Filter buildDiscriminatorFilter(Query query, ClassDescriptor classDescriptor) { + Filter discriminatorFilter = this.createFilter(query.getFilter().getFilterClass()); + if (!classDescriptor.isAbstract() && (! classDescriptor.isInterface()) ) { + discriminatorFilter.addJCRExpression("@" + ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY + "='" + classDescriptor.getClassName() + "'"); + } + + if (classDescriptor.hasDescendants()) { + Iterator descendantDescriptorIterator = classDescriptor.getDescendantClassDescriptors().iterator(); + + while (descendantDescriptorIterator.hasNext()) { + ClassDescriptor descendantClassDescriptor = (ClassDescriptor) descendantDescriptorIterator.next(); + + //Add subdescendant discriminator value + discriminatorFilter = discriminatorFilter.addOrFilter( + this.buildDiscriminatorFilter(query, descendantClassDescriptor)); + } + + } + + return discriminatorFilter; + } + + private String getNodeType(Filter filter) { + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(filter.getFilterClass()); + + String jcrNodeType = classDescriptor.getJcrType(); + if (jcrNodeType == null || jcrNodeType.equals("")) + { + return ManagerConstant.NT_UNSTRUCTURED; + } + else + { + return jcrNodeType; + } + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/reflection/ReflectionUtils.java b/src/main/java/org/apache/jackrabbit/ocm/reflection/ReflectionUtils.java new file mode 100644 index 00000000..97a2c80d --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/reflection/ReflectionUtils.java @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.reflection; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.apache.commons.beanutils.ConstructorUtils; +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; + +import net.sf.cglib.proxy.Enhancer; + + +/** + * Utility class for handling reflection using BeanUtils. + * + * @author Alexandru Popescu + */ +abstract public class ReflectionUtils { + + // default the class loader to the load of this class + private static ClassLoader classLoader = ReflectionUtils.class.getClassLoader(); + + // key = interface class, value = default implementation for the interface + // TODO : inject this map when the object content manager is initialized + private static HashMap defaultImplementation; + + static { + defaultImplementation = new HashMap(); + defaultImplementation.put(Collection.class, ArrayList.class); + defaultImplementation.put(List.class, ArrayList.class); + defaultImplementation.put(Map.class, HashMap.class); + defaultImplementation.put(SortedMap.class, TreeMap.class); + defaultImplementation.put(Set.class, HashSet.class); + + } + /** + * Sets the class loader to use in the {@link #forName(String)} method to + * load classes. + *

+ * Care must be taken when using this method as when setting an improperly + * set up classloader, the mapper will not work again throwing tons of + * exceptions. + * + * @param newClassLoader The new class loader to use. This may be + * null in which case the system class loader will be used. + */ + public static void setClassLoader(ClassLoader newClassLoader) { + classLoader = newClassLoader; + } + + /** + * Returns the class loader which is used by the {@link #forName(String)} + * method to load classes. + * + * @return The class loader used by {@link #forName(String)} or + * null if the system class loader is used. + */ + public static ClassLoader getClassLoader() { + return classLoader; + } + + public static Object getNestedProperty(Object object, String fieldName) { + if (null == object) { + return null; + } + + try { + return PropertyUtils.getNestedProperty(object, fieldName); + } + catch(IllegalAccessException e) { + throw new JcrMappingException("Cannot access property " + + fieldName, + e); + } + catch(InvocationTargetException e) { + throw new JcrMappingException("Cannot access property " + + fieldName, + e); + } + catch(NoSuchMethodException e) { + throw new JcrMappingException("Cannot access property " + + fieldName, + e); + } + } + + public static Class getPropertyType(Object object, String fieldName) { + try { + return PropertyUtils.getPropertyType(object, fieldName); + } + catch(Exception ex) { + throw new JcrMappingException("Cannot access property " + + fieldName, + ex); + } + } + + public static Object newInstance(Class clazz) { + try { + return clazz.newInstance(); + } + catch(Exception ex) { + throw new JcrMappingException("Cannot create instance for class " + + clazz, + ex); + } + } + + /** + * @param className + * @param objects + * @return + */ + public static Object invokeConstructor(String className, Object[] params) { + try { + Class converterClass= forName(className); + + return ConstructorUtils.invokeConstructor(converterClass, params); + } + catch(Exception ex) { + throw new JcrMappingException("Cannot create instance for class " + className, ex); + } + } + + /** + * @param object + * @param fieldName + * @param path + */ + public static void setNestedProperty(Object object, String fieldName, Object value) { + try { + PropertyUtils.setNestedProperty(object, fieldName, value); + } + catch(Exception ex) { + // IGNORE to support loading old objects into new structures. + } + } + + /** + * @param string + * @return + */ + public static Object newInstance(String clazz) { + try { + return forName(clazz).newInstance(); + } + catch(Exception ex) { + throw new JcrMappingException("Cannot create instance for class " + clazz, ex); + } + } + + /** + * @param elementClassName + * @return + */ + public static Class forName(String clazz) { + try { + return Class.forName(clazz, true, getClassLoader()); + } + catch(Exception ex) { + throw new JcrMappingException("Cannot load class " + clazz, ex); + } + } + + public static boolean isProxy(Class beanClass) + { + return Enhancer.isEnhanced(beanClass); + } + + public static Class getBeanClass(Object bean) + { + Class beanClass = bean.getClass(); + if (isProxy(beanClass)) + { + //CGLIB specific + return beanClass.getSuperclass(); + } + return beanClass; + } + + + /** + * Check if an class is implementing an specific interface. + * + * @param clazz + * @param interfaceClass + * @return true if the class is implementing the interface otherwise false + */ + public static boolean implementsInterface(Class clazz, Class interfaceClass) { + + // Try to find the interface class in the interfaces list + if (clazz.getInterfaces() != null) { + for (Class foundInterface : clazz.getInterfaces()) { + if (foundInterface == interfaceClass + || implementsInterface(foundInterface, interfaceClass)) { + return true; + } + } + } + // Try to find from the ancestors + if (clazz.getSuperclass() != null) { + return implementsInterface(clazz.getSuperclass(), interfaceClass); + } + return false; + } + + /** + * Get the default implementation for an interface + * @param clazz The interface clazz + * @return The class matching to the interface default interface + */ + public static Class getDefaultImplementation(Class clazz) + { + if (! clazz.isInterface()) + throw new JcrMappingException(clazz + " is not an interface"); + + return defaultImplementation.get(clazz); + } + + public static boolean isAbstractClass(Class clazz) + { + return Modifier.isAbstract(clazz.getModifiers()); + } + + public static Class getAncestorClass(Class clazz) + { + Class ancestorClass = clazz.getSuperclass(); + if (ancestorClass == Object.class) + return null; + else + return ancestorClass; + } + + + public static Class[] getInterfaces(Class clazz) + { + return clazz.getInterfaces(); + } + +} diff --git a/src/main/java/org/apache/jackrabbit/ocm/repository/NodeUtil.java b/src/main/java/org/apache/jackrabbit/ocm/repository/NodeUtil.java new file mode 100644 index 00000000..42783016 --- /dev/null +++ b/src/main/java/org/apache/jackrabbit/ocm/repository/NodeUtil.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.repository; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** +* Utility class for managing JCR nodes. +* +* +* @author Lombart Christophe +* @version $Id: Exp $ +*/ +public class NodeUtil +{ + + + /** Item path separator */ + public static final String PATH_SEPARATOR = "/"; + + private final static Logger log = LoggerFactory.getLogger(NodeUtil.class); + + + /** + * Check if a path is valid + * + * @param path The path to validate + * @return true if the path is valid, else false + */ + public static boolean isValidPath(String path) + { + if ((path == null) || + (path.equals(PATH_SEPARATOR)) || + (path.endsWith(PATH_SEPARATOR)) || + (! path.startsWith(PATH_SEPARATOR)) || + (path.equals(""))) + { + return false; + } + return true; + } + + /** + * Get the parent path + * @param path The path from wich the parent path has to be returned + * @return The parent path + * + * @throws ObjectContentManagerException when the path is invalid + */ + public static String getParentPath(String path) throws ObjectContentManagerException + { + String parentPath = ""; + + if (!isValidPath(path)) + { + throw new JcrMappingException("Invalid path : " + path); + } + + String[] pathElements = path.split(PATH_SEPARATOR); + + // Firts path element should be = empty string because a uri always start with '/' + // So, if len=2, means it is a root folder like '/foo'. + // In this case the uri has not parent folder => return "/" + if (pathElements.length == 2) + { + return PATH_SEPARATOR; + } + + for(int i=0; i < pathElements.length -1; i++) + { + if (! pathElements[i].equals("")) + { + parentPath += PATH_SEPARATOR + pathElements[i]; + } + } + return parentPath; + } + + /** + * Get the node name + * @param path The path from which the node name has to be retrieved + * @return The node name + * + * @throws ObjectContentManagerException when the path is invalid + */ + public static String getNodeName(String path) throws ObjectContentManagerException + { + + String[] pathElements = path.split(PATH_SEPARATOR); + + if (! isValidPath(path)) + { + throw new JcrMappingException("Invalid path : " + path); + } + return pathElements[pathElements.length-1]; + } + + +} diff --git a/src/java/org/apache/portals/graffito/jcr/version/Version.java b/src/main/java/org/apache/jackrabbit/ocm/version/Version.java similarity index 72% rename from src/java/org/apache/portals/graffito/jcr/version/Version.java rename to src/main/java/org/apache/jackrabbit/ocm/version/Version.java index edd387ea..408c6b3e 100644 --- a/src/java/org/apache/portals/graffito/jcr/version/Version.java +++ b/src/main/java/org/apache/jackrabbit/ocm/version/Version.java @@ -1,93 +1,94 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.version; - -import java.util.Calendar; - -import javax.jcr.RepositoryException; - -import org.apache.portals.graffito.jcr.exception.VersionException; - -/** - * - * - * @author Lombart Christophe - * - */ -public class Version -{ - - private javax.jcr.version.Version version; - - public Version(javax.jcr.version.Version version) - { - this.version = version; - } - - public Calendar getCreated() - { - try - { - return version.getCreated(); - } - catch (RepositoryException e) - { - - throw new VersionException("Error while retrieving the version creation date", e); - } - } - - public String getUuid() - { - try - { - return version.getUUID(); - } - catch (RepositoryException e) - { - - throw new VersionException("Error while retrieving the version UUID", e); - } - } - - public String getPath() - { - try - { - return version.getPath(); - } - catch (RepositoryException e) - { - - throw new VersionException("Error while retrieving the version path", e); - } - } - - public String getName() - { - try - { - return version.getName(); - - } - catch (RepositoryException e) - { - - throw new VersionException("Error while retrieving the version path", e); - } - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.version; + +import java.util.Calendar; + +import javax.jcr.RepositoryException; + +import org.apache.jackrabbit.ocm.exception.VersionException; + +/** + * + * + * @author Lombart Christophe + * + */ +public class Version +{ + + private javax.jcr.version.Version version; + + public Version(javax.jcr.version.Version version) + { + this.version = version; + } + + public Calendar getCreated() + { + try + { + return version.getCreated(); + } + catch (RepositoryException e) + { + + throw new VersionException("Error while retrieving the version creation date", e); + } + } + + public String getUuid() + { + try + { + return version.getIdentifier(); + } + catch (RepositoryException e) + { + + throw new VersionException("Error while retrieving the version UUID", e); + } + } + + public String getPath() + { + try + { + return version.getPath(); + } + catch (RepositoryException e) + { + + throw new VersionException("Error while retrieving the version path", e); + } + } + + public String getName() + { + try + { + return version.getName(); + + } + catch (RepositoryException e) + { + + throw new VersionException("Error while retrieving the version path", e); + } + } + +} diff --git a/src/java/org/apache/portals/graffito/jcr/version/VersionIterator.java b/src/main/java/org/apache/jackrabbit/ocm/version/VersionIterator.java similarity index 70% rename from src/java/org/apache/portals/graffito/jcr/version/VersionIterator.java rename to src/main/java/org/apache/jackrabbit/ocm/version/VersionIterator.java index a05a5539..b8ae3c1a 100644 --- a/src/java/org/apache/portals/graffito/jcr/version/VersionIterator.java +++ b/src/main/java/org/apache/jackrabbit/ocm/version/VersionIterator.java @@ -1,10 +1,10 @@ /* - * Copyright 2004-2005 The Apache Software Foundation or its licensors, - * as applicable. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -15,7 +15,7 @@ * limitations under the License. */ -package org.apache.portals.graffito.jcr.version; +package org.apache.jackrabbit.ocm.version; import java.util.Iterator; @@ -24,7 +24,7 @@ /** * VersionIterator is a wrapper class for JCR VersionIterator - * + * * @author Christophe Lombart * */ @@ -39,7 +39,7 @@ public VersionIterator(javax.jcr.version.VersionIterator versionIterator) } /** - * + * * @see java.util.Iterator#hasNext() */ public boolean hasNext() @@ -48,16 +48,16 @@ public boolean hasNext() } /** - * + * * @see java.util.Iterator#next() */ - public Object next() + public Object next() { try { Version version = versionIterator.nextVersion(); - return new org.apache.portals.graffito.jcr.version.Version(version); + return new org.apache.jackrabbit.ocm.version.Version(version); } catch (Exception e) { @@ -67,7 +67,7 @@ public Object next() } /** - * + * * @return the versionIterator size */ public long getSize() @@ -76,7 +76,7 @@ public long getSize() } /** - * + * * @see java.util.Iterator#remove() */ public void remove() diff --git a/src/main/resources/META-INF/LICENSE.txt b/src/main/resources/META-INF/LICENSE.txt new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/src/main/resources/META-INF/LICENSE.txt @@ -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/src/main/resources/META-INF/NOTICE.txt b/src/main/resources/META-INF/NOTICE.txt new file mode 100644 index 00000000..514416eb --- /dev/null +++ b/src/main/resources/META-INF/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Jackrabbit Object Content Mapping +Copyright 2009 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/src/main/resources/org/apache/jackrabbit/ocm/config/jackrabbit-ocm-1.4.dtd b/src/main/resources/org/apache/jackrabbit/ocm/config/jackrabbit-ocm-1.4.dtd new file mode 100644 index 00000000..90917a51 --- /dev/null +++ b/src/main/resources/org/apache/jackrabbit/ocm/config/jackrabbit-ocm-1.4.dtd @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/org/apache/jackrabbit/ocm/config/jackrabbit-ocm-1.5.dtd b/src/main/resources/org/apache/jackrabbit/ocm/config/jackrabbit-ocm-1.5.dtd new file mode 100644 index 00000000..25430b22 --- /dev/null +++ b/src/main/resources/org/apache/jackrabbit/ocm/config/jackrabbit-ocm-1.5.dtd @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test-config/jaas.config b/src/test-config/jaas.config deleted file mode 100644 index 94575088..00000000 --- a/src/test-config/jaas.config +++ /dev/null @@ -1,3 +0,0 @@ -Jackrabbit { -org.apache.jackrabbit.core.security.SimpleLoginModule required debug=false; -}; \ No newline at end of file diff --git a/src/test-config/jcrmapping-atomic.xml b/src/test-config/jcrmapping-atomic.xml deleted file mode 100644 index 14070827..00000000 --- a/src/test-config/jcrmapping-atomic.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/test-config/jcrmapping.xml b/src/test-config/jcrmapping.xml deleted file mode 100644 index aee5aef0..00000000 --- a/src/test-config/jcrmapping.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/test-config/repository-derby.xml b/src/test-config/repository-derby.xml deleted file mode 100755 index 013f99e5..00000000 --- a/src/test-config/repository-derby.xml +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test-config/repository-xml.xml b/src/test-config/repository-xml.xml deleted file mode 100755 index 3d4084b1..00000000 --- a/src/test-config/repository-xml.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test-config/repository/repository/nodetypes/custom_nodetypes.xml b/src/test-config/repository/repository/nodetypes/custom_nodetypes.xml deleted file mode 100755 index 5b432bea..00000000 --- a/src/test-config/repository/repository/nodetypes/custom_nodetypes.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - mix:versionable - nt:base - - - - - - - - - mix:versionable - nt:base - - - - - - - - mix:versionable - nt:base - - - - - - graffito:paragraph - - - - - - - mix:versionable - nt:base - - - - - - - diff --git a/src/test-data/data-import.xml b/src/test-data/data-import.xml deleted file mode 100644 index a08a60ca..00000000 --- a/src/test-data/data-import.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/AbstractRepositoryTestBase.java b/src/test/java/org/apache/jackrabbit/ocm/AbstractRepositoryTestBase.java new file mode 100644 index 00000000..b7ac3152 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/AbstractRepositoryTestBase.java @@ -0,0 +1,241 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm; + +import java.io.BufferedOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.Iterator; + +import javax.jcr.Node; +import javax.jcr.NodeIterator; +import javax.jcr.Repository; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.Workspace; +import javax.jcr.nodetype.NoSuchNodeTypeException; +import javax.jcr.nodetype.NodeTypeManager; + +import org.apache.jackrabbit.core.nodetype.InvalidNodeTypeDefException; +import org.apache.jackrabbit.core.nodetype.NodeTypeManagerImpl; +import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry; +import org.apache.jackrabbit.core.nodetype.xml.NodeTypeReader; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.reflection.ReflectionUtils; +import org.apache.jackrabbit.spi.QNodeTypeDefinition; +import org.apache.jackrabbit.test.AbstractJCRTest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractRepositoryTestBase extends AbstractJCRTest { + + + private final static Logger log = LoggerFactory.getLogger(AbstractRepositoryTestBase.class); + + /** namespace prefix constant */ + public static final String OCM_NAMESPACE_PREFIX = "ocm"; + + public static Repository repository; + + /** namespace constant */ + public static final String OCM_NAMESPACE = "http://jackrabbit.apache.org/ocm"; + + private ObjectContentManager ocm; + + private Session session; + + @Override + protected void setUp() throws Exception { + super.setUp(); + Session session = createSession(); + + registerNamespace(session); + registerNodeTypes(session); + session.save(); + session.logout(); + ocm = createObjectContentManager(getSession()); + } + + protected abstract ObjectContentManager createObjectContentManager(Session session) throws javax.jcr.RepositoryException; + + public ObjectContentManager getObjectContentManager() + { + return ocm; + } + + @Override + public void tearDown() throws Exception { + if (session != null) { + session.logout(); + } + cleanUpRepisotory(); + super.tearDown(); + } + + /** + * + * @return a readWrite session and creates a new one if this method is called for the first time for this AbstractRepositoryTestBase + */ + protected Session getSession() { + if (session != null) { + return session; + } + session = createSession(); + return session; + } + + private Session createSession() { + try { + return getHelper().getReadWriteSession(); + } catch (RepositoryException e) { + throw new IllegalStateException("Could not get a jcr session", e); + } + } + + protected void cleanUpRepisotory() + { + try + { + Session session = createSession(); + NodeIterator nodeIterator = session.getRootNode().getNodes(); + + while (nodeIterator.hasNext()) + { + Node node = nodeIterator.nextNode(); + if (! node.getName().startsWith("jcr:") && ! node.getName().startsWith("rep:")) + { + log.debug("tearDown - remove : " + node.getPath()); + node.remove(); + } + } + session.save(); + session.logout(); + } + catch(Exception e) + { + log.error("cleanUpRepository failed", e); + } + } + + public void exportDocument(String filePath, String nodePath, boolean skipBinary, boolean noRecurse) + { + try + { + BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(filePath)); + Session session = getSession(); + session.exportDocumentView(nodePath, os, skipBinary, noRecurse); + os.flush(); + os.close(); + session.logout(); + } + catch (Exception e) + { + log.error("Impossible to export the content from : " + nodePath, e); + } + } + + protected void registerNamespace(final Session session) throws javax.jcr.RepositoryException { + log.info("Register namespace"); + String[] jcrNamespaces = session.getWorkspace().getNamespaceRegistry().getPrefixes(); + boolean createNamespace = true; + for (int i = 0; i < jcrNamespaces.length; i++) { + if (jcrNamespaces[i].equals(OCM_NAMESPACE_PREFIX)) { + createNamespace = false; + log.debug("Jackrabbit OCM namespace exists."); + } + } + if (createNamespace) { + session.getWorkspace().getNamespaceRegistry().registerNamespace(OCM_NAMESPACE_PREFIX, OCM_NAMESPACE); + log.info("Successfully created Jackrabbit OCM namespace."); + } + + if (session.getRootNode() != null) { + log.info("Jcr session setup successfull."); + } + } + + protected void registerNodeTypes(Session session) + throws InvalidNodeTypeDefException, javax.jcr.RepositoryException, IOException { + InputStream xml = new FileInputStream( + "./src/test/test-config/nodetypes/custom_nodetypes.xml"); + + // HINT: throws InvalidNodeTypeDefException, IOException + QNodeTypeDefinition[] types = NodeTypeReader.read(xml); + + Workspace workspace = session.getWorkspace(); + NodeTypeManager ntMgr = workspace.getNodeTypeManager(); + NodeTypeRegistry ntReg = ((NodeTypeManagerImpl) ntMgr).getNodeTypeRegistry(); + + for (int j = 0; j < types.length; j++) { + QNodeTypeDefinition def = types[j]; + + try { + ntReg.getNodeTypeDef(def.getName()); + } catch (NoSuchNodeTypeException nsne) { + // HINT: if not already registered than register custom node type + ntReg.registerNodeType(def); + } + + } + } + + protected boolean contains(Collection result, String path, Class objectClass) + { + Iterator iterator = result.iterator(); + while (iterator.hasNext()) + { + Object object = iterator.next(); + String itemPath = (String) ReflectionUtils.getNestedProperty(object, "path"); + if (itemPath.equals(path)) + { + if (object.getClass() == objectClass) + { + return true; + } + else + { + return false; + } + + } + } + return false; + } + + + /** + * utility method to easily print an overview the repository contents + * @param node + * @param indent + * @throws RepositoryException + */ + protected void traverse(final Node node, String indent) throws RepositoryException { + if (node.getPath().equals("/jcr:system")) { + return; + } + System.out.println(indent + node.getPath() + " [ "+ node.getPrimaryNodeType().getName() + " ] "); + indent = indent + "\t"; + NodeIterator it = node.getNodes(); + while (it.hasNext()) { + traverse(it.nextNode(), indent); + } + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/AllTests.java new file mode 100644 index 00000000..dccfb2ab --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/AllTests.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * OCM suite definition. Bundles together all independent and package level test suites. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() throws Exception { + return buildSuite(); + } + + public static Test buildSuite() throws Exception { + TestSuite suite= new TestSuite("Jackrabbit OCM Tests"); + + suite.addTest(org.apache.jackrabbit.ocm.manager.atomic.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.auto.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.basic.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.beanconverter.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.collectionconverter.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.inheritance.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.interfaces.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.jcrnodetype.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.lock.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.proxy.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.query.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.uuid.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.manager.version.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.mapper.AllTests.buildSuite()); + suite.addTest(org.apache.jackrabbit.ocm.querymanager.AllTests.buildSuite()); + + return suite; + } +} + diff --git a/src/test/java/org/apache/jackrabbit/ocm/AnnotationRepositoryTestBase.java b/src/test/java/org/apache/jackrabbit/ocm/AnnotationRepositoryTestBase.java new file mode 100644 index 00000000..ab134f51 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/AnnotationRepositoryTestBase.java @@ -0,0 +1,172 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm; + +import java.util.ArrayList; +import java.util.List; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.AnnotationMapperImpl; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.D; +import org.apache.jackrabbit.ocm.testmodel.DFull; +import org.apache.jackrabbit.ocm.testmodel.Default; +import org.apache.jackrabbit.ocm.testmodel.Discriminator; +import org.apache.jackrabbit.ocm.testmodel.E; +import org.apache.jackrabbit.ocm.testmodel.File; +import org.apache.jackrabbit.ocm.testmodel.HierarchyNode; +import org.apache.jackrabbit.ocm.testmodel.Lockable; +import org.apache.jackrabbit.ocm.testmodel.MultiValue; +import org.apache.jackrabbit.ocm.testmodel.MultiValueWithObjectCollection; +import org.apache.jackrabbit.ocm.testmodel.OcmTestProperty; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.testmodel.Residual; +import org.apache.jackrabbit.ocm.testmodel.Resource; +import org.apache.jackrabbit.ocm.testmodel.SimpleAnnotedAbstractClass; +import org.apache.jackrabbit.ocm.testmodel.SimpleAnnotedClass; +import org.apache.jackrabbit.ocm.testmodel.SimpleInterface; +import org.apache.jackrabbit.ocm.testmodel.collection.Element; +import org.apache.jackrabbit.ocm.testmodel.collection.Main; +import org.apache.jackrabbit.ocm.testmodel.collection.Person; +import org.apache.jackrabbit.ocm.testmodel.enumeration.Odyssey; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.CmsObjectImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.ContentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentExtImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.FolderImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.AnotherInterface; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Content; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Document; +import org.apache.jackrabbit.ocm.testmodel.interfaces.EntityA; +import org.apache.jackrabbit.ocm.testmodel.interfaces.EntityB; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; +import org.apache.jackrabbit.ocm.testmodel.interfaces.MyInterface; +import org.apache.jackrabbit.ocm.testmodel.version.Author; +import org.apache.jackrabbit.ocm.testmodel.version.PressRelease; + +/** + * Base class for testcases. Provides priviledged access to the jcr test + * repository. + * + * @author Christophe Lombart + * @author : Boni Gopalan + * + */ +public abstract class AnnotationRepositoryTestBase extends AbstractRepositoryTestBase +{ + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException + { + List classes = new ArrayList(); + + // Register content classes used by the unit tests + classes.add(Atomic.class); + classes.add(Default.class); + classes.add(A.class); + classes.add(B.class); + classes.add(C.class); + classes.add(D.class); + classes.add(DFull.class); + classes.add(E.class); + classes.add(Page.class); + classes.add(Paragraph.class); + classes.add(Main.class); + classes.add(Element.class); + classes.add(MultiValue.class); + classes.add(MultiValueWithObjectCollection.class); + classes.add(Discriminator.class); + + classes.add(Residual.class); + classes.add(Residual.ResidualProperties.class); + classes.add(Residual.ResidualNodes.class); + + classes.add(CmsObject.class); + classes.add(Content.class); + classes.add(Document.class); + classes.add(Folder.class); + classes.add(CmsObjectImpl.class); + classes.add(ContentImpl.class); + classes.add(DocumentImpl.class); + classes.add(DocumentExtImpl.class); + classes.add(DocumentStream.class); + classes.add(FolderImpl.class); + + classes.add(Ancestor.class); + classes.add(Descendant.class); + classes.add(AnotherDescendant.class); + classes.add(SubDescendant.class); + classes.add(Interface.class); + classes.add(AnotherInterface.class); + + classes.add(HierarchyNode.class); + classes.add(File.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.Folder.class); + classes.add(Resource.class); + classes.add(OcmTestProperty.class); + + classes.add(Lockable.class); + + classes.add(org.apache.jackrabbit.ocm.testmodel.proxy.Main.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.proxy.Detail.class); + + classes.add(org.apache.jackrabbit.ocm.testmodel.proxy.NTMain.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.proxy.NTDetail.class); + + classes.add(org.apache.jackrabbit.ocm.testmodel.uuid.A.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.uuid.B.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.uuid.B2.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.uuid.Ancestor.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.uuid.Descendant.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.unstructured.UnstructuredParagraph.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.unstructured.UnstructuredPage.class); + + classes.add(PressRelease.class); + classes.add(Author.class); + + classes.add(SimpleAnnotedAbstractClass.class); + classes.add(SimpleAnnotedClass.class); + classes.add(SimpleInterface.class); + classes.add(Person.class); + classes.add(Odyssey.class); + + classes.add(EntityA.class); + classes.add(EntityB.class); + classes.add(MyInterface.class); + + Mapper mapper = new AnnotationMapperImpl(classes); + return new ObjectContentManagerImpl(session, mapper); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/DigesterRepositoryTestBase.java b/src/test/java/org/apache/jackrabbit/ocm/DigesterRepositoryTestBase.java new file mode 100644 index 00000000..77845a1b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/DigesterRepositoryTestBase.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; + +/** + * Base class for testcases. Provides priviledged access to the jcr test + * repository. + * + * @author Christophe Lombart + * + * + */ +public abstract class DigesterRepositoryTestBase extends AbstractRepositoryTestBase +{ + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException + { + String[] files = { "./src/test/test-config/jcrmapping.xml", + "./src/test/test-config/jcrmapping-proxy.xml", + "./src/test/test-config/jcrmapping-atomic.xml", + "./src/test/test-config/jcrmapping-default.xml", + "./src/test/test-config/jcrmapping-beandescriptor.xml", + "./src/test/test-config/jcrmapping-inheritance.xml", + "./src/test/test-config/jcrmapping-jcrnodetypes.xml", + "./src/test/test-config/jcrmapping-uuid.xml", + "./src/test/test-config/jcrmapping-complex-collections.xml", + "./src/test/test-config/jcrmapping-Enum.xml" + }; + + return new ObjectContentManagerImpl(session, files); + + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/NodeUtilTest.java b/src/test/java/org/apache/jackrabbit/ocm/NodeUtilTest.java new file mode 100644 index 00000000..0cd56d1d --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/NodeUtilTest.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm; + +import junit.framework.TestCase; + +import org.apache.jackrabbit.ocm.repository.NodeUtil; + +/** Testcase for RepositoryUtil. + * + * @author Christophe Lombart + * @author Alexandru Popescu + */ +public class NodeUtilTest extends TestCase +{ + + + public NodeUtilTest(String testName) + { + super(testName); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + public void tearDown() throws Exception + { + super.tearDown(); + } + + + /** + * Test for getParentPath() + * + */ + public void testGetParentPath() + { + try + { + String parentPath = NodeUtil.getParentPath("/test"); + assertNotNull("parent path is null for /test", parentPath); + assertTrue("parent path is incorrect for /test", parentPath.equals("/")); + + parentPath = NodeUtil.getParentPath("/test/test2"); + assertNotNull("parent path is null for /test/test2", parentPath); + assertTrue("parent path is incorrect for /test/test2", parentPath.equals("/test")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Unable to find the repository : " + e); + } + } + + /** + * Test for getNodeName() + * + */ + public void testGetNodeName() + { + try + { + String nodeName = NodeUtil.getNodeName("/test"); + assertNotNull("node name is null for /test", nodeName); + assertTrue("node name is incorrect for /test", nodeName.equals("test")); + + nodeName = NodeUtil.getNodeName("/test/test2"); + assertNotNull("node name is null for /test/test2", nodeName); + assertTrue("node name is incorrect for /test/test2", nodeName.equals("test2")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Unable to find the repository : " + e); + } + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AllTests.java new file mode 100644 index 00000000..6fc959cd --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AllTests.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomic; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.jcr.manager.atomic"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationAtomicTest.class); + suite.addTestSuite(AnnotationNullAtomicTest.class); + suite.addTestSuite(AnnotationDefaultValueTest.class); + suite.addTestSuite(DigesterAtomicTest.class); + suite.addTestSuite(DigesterNullAtomicTest.class); + suite.addTestSuite(DigesterDefaultValueTest.class); + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationAtomicTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationAtomicTest.java new file mode 100644 index 00000000..7b4e6e53 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationAtomicTest.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomic; + +import java.io.ByteArrayInputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Date; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test atomic persistence fields + * + * @author Christophe Lombart + */ +public class AnnotationAtomicTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationAtomicTest.class); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationAtomicTest.class); + } + + + public void testAtomicFields() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + Date date = new Date(); + Calendar calendar = Calendar.getInstance(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + Atomic a = new Atomic(); + a.setPath("/test"); + a.setBooleanObject(new Boolean(true)); + a.setBooleanPrimitive(true); + a.setIntegerObject(new Integer(100)); + a.setIntPrimitive(200); + a.setString("Test String"); + a.setDate(date); + a.setInt2boolean(true); + + byte[] content = "Test Byte".getBytes(); + a.setByteArray(content); + a.setCalendar(calendar); + a.setDoubleObject(new Double(2.12)); + a.setDoublePrimitive(1.23); + long now = System.currentTimeMillis(); + a.setTimestamp(new Timestamp(now)); + + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("Test Stream".getBytes()); + a.setInputStream(byteArrayInputStream); + a.setNamedProperty("ocm:test"); + a.setPathProperty("/node1/node2"); + a.setUndefinedProperty("aStringData"); + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (Atomic) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertNotNull("Boolean object is null", a.getBooleanObject()); + assertTrue("Incorrect boolean object", a.getBooleanObject().booleanValue()); + assertTrue("Incorrect boolean primitive", a.isBooleanPrimitive()); + assertNotNull("Integer Object is null", a.getIntegerObject()); + assertTrue("Incorrect Integer object", a.getIntegerObject().intValue() == 100); + assertTrue("Incorrect int primitive", a.getIntPrimitive() == 200); + assertNotNull("String object is null", a.getString()); + assertTrue("Incorrect boolean object", a.getString().equals("Test String")); + assertNotNull("Byte array object is null", a.getByteArray()); + assertTrue("Incorrect byte object", new String(a.getByteArray()).equals("Test Byte")); + + assertNotNull("date object is null", a.getDate()); + assertTrue("Invalid date", a.getDate().equals(date)); + assertNotNull("calendar object is null", a.getCalendar()); + + log.debug("Calendar : " + a.getCalendar().get(Calendar.YEAR) + "-" + a.getCalendar().get(Calendar.MONTH) + "-" + a.getCalendar().get(Calendar.DAY_OF_MONTH)); + assertTrue("Invalid calendar object", a.getCalendar().equals(calendar)); + + assertNotNull("Double object is null", a.getDoubleObject()); + assertTrue("Incorrect double object", a.getDoubleObject().doubleValue() == 2.12); + assertTrue("Incorrect double primitive", a.getDoublePrimitive() == 1.23); + + assertNotNull("Incorrect input stream primitive", a.getInputStream()); + assertNotNull("Incorrect timestamp", a.getTimestamp()); + assertTrue("Invalid timestamp value ", a.getTimestamp().getTime() == now); + assertTrue("Invalid int2boolean value ", a.isInt2boolean()); + + assertTrue("Invalid namedProperty value ", a.getNamedProperty().equals("ocm:test")); + assertTrue("Invalid pathProperty value ", a.getPathProperty().equals("/node1/node2")); + assertTrue("Invalid undefinedProperty value ", ((String) a.getUndefinedProperty()).equals("aStringData")); + // -------------------------------------------------------------------------------- + // Update the property "namedProperty" with an invalid value + // -------------------------------------------------------------------------------- + try + { + // update with an incorrect namespace - Should throw an exception + a.setNamedProperty("unknown:test"); + ocm.update(a); + fail("Exception was not triggered with an invalid namespace"); + ocm.save(); + } + catch (Exception e) + { + + + } + + // -------------------------------------------------------------------------------- + // Update the property "pathProperty" with an invalid value + // -------------------------------------------------------------------------------- + try + { + // update with an incorrect path - Should throw an exception + a.setPathProperty("//node1"); + ocm.update(a); + fail("Exception was not triggered with an invalid path"); + ocm.save(); + } + catch (Exception e) + { + + + } + + // -------------------------------------------------------------------------------- + // Update the property "undefinedProperty" with an invalid value + // -------------------------------------------------------------------------------- + a = null; + a = (Atomic) ocm.getObject( "/test"); + + a.setUndefinedProperty(new Double(1.2)); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (Atomic) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertTrue("Invalid undefinedProperty value ", ((Double) a.getUndefinedProperty()).doubleValue() == 1.2); + + } + catch (Exception e) + { + log.error("testAtomicFields failed", e); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationDefaultValueTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationDefaultValueTest.java new file mode 100644 index 00000000..ea05e5b3 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationDefaultValueTest.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomic; + +import javax.jcr.Node; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Default; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test Default value assignement + */ +public class AnnotationDefaultValueTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationDefaultValueTest.class); + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationDefaultValueTest.class); + } + + public void testDefaultValues() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + Default a = new Default(); + a.setPath("/testDefault"); + a.setP1("p1Value"); + // do not set p2, p3, p4, p5 + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (Default) ocm.getObject( "/testDefault" ); + assertNotNull("a is null", a); + + assertEquals("p1Value", a.getP1()); + assertNull(a.getP2()); + assertEquals("p3DescriptorDefaultValue", a.getP3()); + assertEquals("p4DefaultValue", a.getP4()); + assertEquals("p5DefaultValue", a.getP5()); + + } + catch (Exception e) + { + log.error("testDefaultValues failed", e); + fail("Exception occurs during the unit test : " + e); + } + + } + + + public void testDefaultValuesRead() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Manually create a node + // we need this test as SimpleFieldsHelper.storeSimpleField sets the + // property value if the field is not set but a jcrDefaultValue + // is set. But we want to test, that SimpleFieldsHelper.retrieveSimpleField + // sets the default value from the jcrDefaultValue + // -------------------------------------------------------------------------------- + Node nodeA = ocm.getSession().getRootNode().addNode("testDefault", "ocm:DefTestPrimary"); + nodeA.setProperty("ocm:p1", "p1Value"); + ocm.getSession().save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + Default a = (Default) ocm.getObject( "/testDefault" ); + assertNotNull("a is null", a); + + assertEquals("p1Value", a.getP1()); + assertNull(a.getP2()); + assertEquals("p3DescriptorDefaultValue", a.getP3()); + assertEquals("p4DefaultValue", a.getP4()); + assertEquals("p5DefaultValue", a.getP5()); + + } + catch (Exception e) + { + log.error("testDefaultValuesRead failed", e); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationNullAtomicTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationNullAtomicTest.java new file mode 100644 index 00000000..ece5638e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/AnnotationNullAtomicTest.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomic; + +import java.io.ByteArrayInputStream; +import java.util.Calendar; +import java.util.Date; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test Atomic perisstence fields + * + * @author Christophe Lombart + */ +public class AnnotationNullAtomicTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationNullAtomicTest.class); + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationNullAtomicTest.class); + } + + + public void testNullValueAtomicFields() + { + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + Atomic a = new Atomic(); + a.setPath("/test"); + a.setIntegerObject(new Integer(100)); + a.setDate(new Date()); + byte[] content = "Test Byte".getBytes(); + a.setByteArray(content); + a.setCalendar(Calendar.getInstance()); + a.setDoubleObject(new Double(2.12)); + a.setDoublePrimitive(1.23); + + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("Test Stream".getBytes()); + a.setInputStream(byteArrayInputStream); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (Atomic) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertNull("Boolean object is not null", a.getBooleanObject()); + + assertFalse("Incorrect boolean primitive", a.isBooleanPrimitive()); + assertNotNull("Integer Object is null", a.getIntegerObject()); + assertTrue("Incorrect Integer object", a.getIntegerObject().intValue() == 100); + assertTrue("Incorrect int primitive", a.getIntPrimitive() == 0); + assertNull("String object is not null", a.getString()); + assertNotNull("Byte array object is null", a.getByteArray()); + assertTrue("Incorrect byte object", new String(a.getByteArray()).equals("Test Byte")); + + assertNotNull("date object is null", a.getDate()); + assertNotNull("calendar object is null", a.getCalendar()); + + assertNotNull("Double object is null", a.getDoubleObject()); + assertTrue("Incorrect double object", a.getDoubleObject().doubleValue() == 2.12); + assertTrue("Incorrect double primitive", a.getDoublePrimitive() == 1.23); + + assertNotNull("Incorrect input stream primitive", a.getInputStream()); + + + } + catch (Exception e) + { + log.error("testNullValueAtomicFields failed", e); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/atomicconverter/AtomicTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterAtomicTest.java similarity index 51% rename from src/test/org/apache/portals/graffito/jcr/persistence/atomicconverter/AtomicTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterAtomicTest.java index f6874277..1820321e 100644 --- a/src/test/org/apache/portals/graffito/jcr/persistence/atomicconverter/AtomicTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterAtomicTest.java @@ -1,20 +1,20 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.atomicconverter; +package org.apache.jackrabbit.ocm.manager.atomic; import java.io.ByteArrayInputStream; import java.sql.Timestamp; @@ -24,56 +24,33 @@ import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.Atomic; +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * Test Atomic perisstence fields + * Test atomic persistence fields * * @author Christophe Lombart */ -public class AtomicTest extends TestBase +public class DigesterAtomicTest extends DigesterRepositoryTestBase { - private final static Log log = LogFactory.getLog(AtomicTest.class); + private final static Logger log = LoggerFactory.getLogger(DigesterAtomicTest.class); - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public AtomicTest(String testName) throws Exception - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(AtomicTest.class); + return new TestSuite(DigesterAtomicTest.class); } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - - super.tearDown(); - } - public void testAtomicFields() { try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); Date date = new Date(); Calendar calendar = Calendar.getInstance(); // -------------------------------------------------------------------------------- @@ -87,7 +64,8 @@ public void testAtomicFields() a.setIntPrimitive(200); a.setString("Test String"); a.setDate(date); - + a.setInt2boolean(true); + byte[] content = "Test Byte".getBytes(); a.setByteArray(content); a.setCalendar(calendar); @@ -95,19 +73,22 @@ public void testAtomicFields() a.setDoublePrimitive(1.23); long now = System.currentTimeMillis(); a.setTimestamp(new Timestamp(now)); - + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("Test Stream".getBytes()); a.setInputStream(byteArrayInputStream); - - persistenceManager.insert(a); - persistenceManager.save(); + a.setNamedProperty("ocm:test"); + a.setPathProperty("/node1/node2"); + a.setUndefinedProperty("aStringData"); + + ocm.insert(a); + ocm.save(); + - // -------------------------------------------------------------------------------- // Get the object // -------------------------------------------------------------------------------- a = null; - a = (Atomic) persistenceManager.getObject(Atomic.class, "/test"); + a = (Atomic) ocm.getObject( "/test"); assertNotNull("a is null", a); assertNotNull("Boolean object is null", a.getBooleanObject()); assertTrue("Incorrect boolean object", a.getBooleanObject().booleanValue()); @@ -119,29 +100,85 @@ public void testAtomicFields() assertTrue("Incorrect boolean object", a.getString().equals("Test String")); assertNotNull("Byte array object is null", a.getByteArray()); assertTrue("Incorrect byte object", new String(a.getByteArray()).equals("Test Byte")); - + assertNotNull("date object is null", a.getDate()); - assertTrue("Invalid date", a.getDate().equals(date)); + assertTrue("Invalid date", a.getDate().equals(date)); assertNotNull("calendar object is null", a.getCalendar()); - + log.debug("Calendar : " + a.getCalendar().get(Calendar.YEAR) + "-" + a.getCalendar().get(Calendar.MONTH) + "-" + a.getCalendar().get(Calendar.DAY_OF_MONTH)); assertTrue("Invalid calendar object", a.getCalendar().equals(calendar)); - + assertNotNull("Double object is null", a.getDoubleObject()); assertTrue("Incorrect double object", a.getDoubleObject().doubleValue() == 2.12); assertTrue("Incorrect double primitive", a.getDoublePrimitive() == 1.23); - + assertNotNull("Incorrect input stream primitive", a.getInputStream()); assertNotNull("Incorrect timestamp", a.getTimestamp()); - assertTrue("Invalid timestamp value ", a.getTimestamp().getTime() == now); - + assertTrue("Invalid timestamp value ", a.getTimestamp().getTime() == now); + assertTrue("Invalid int2boolean value ", a.isInt2boolean()); + + assertTrue("Invalid namedProperty value ", a.getNamedProperty().equals("ocm:test")); + assertTrue("Invalid pathProperty value ", a.getPathProperty().equals("/node1/node2")); + assertTrue("Invalid undefinedProperty value ", ((String) a.getUndefinedProperty()).equals("aStringData")); + // -------------------------------------------------------------------------------- + // Update the property "namedProperty" with an invalid value + // -------------------------------------------------------------------------------- + try + { + // update with an incorrect namespace - Should throws an exception + a.setNamedProperty("unknown:test"); + ocm.update(a); + fail("Exception was not triggered with an invalid namespace"); + ocm.save(); + } + catch (Exception e) + { + + + } + + // -------------------------------------------------------------------------------- + // Update the property "pathProperty" with an invalid value + // -------------------------------------------------------------------------------- + try + { + // update with an incorrect namespace - Should throws an exception + a.setPathProperty("//node1"); + ocm.update(a); + fail("Exception was not triggered with an invalid path"); + ocm.save(); + } + catch (Exception e) + { + + + } + + // -------------------------------------------------------------------------------- + // Update the property "undefinedProperty" with an invalid value + // -------------------------------------------------------------------------------- + a = null; + a = (Atomic) ocm.getObject( "/test"); + + a.setUndefinedProperty(new Double(1.2)); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (Atomic) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertTrue("Invalid undefinedProperty value ", ((Double) a.getUndefinedProperty()).doubleValue() == 1.2); + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + } - + } \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterDefaultValueTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterDefaultValueTest.java new file mode 100644 index 00000000..2a4652e6 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterDefaultValueTest.java @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.atomic; + +import javax.jcr.Node; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Default; + +/** + * Test Default value assignement + */ +public class DigesterDefaultValueTest extends DigesterRepositoryTestBase +{ + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterDefaultValueTest.class); + } + + public void testDefaultValues() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + Default a = new Default(); + a.setPath("/testDefault"); + a.setP1("p1Value"); + // do not set p2, p3, p4, p5 + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (Default) ocm.getObject( "/testDefault" ); + assertNotNull("a is null", a); + + assertEquals("p1Value", a.getP1()); + assertNull(a.getP2()); + assertEquals("p3DescriptorDefaultValue", a.getP3()); + assertEquals("p4DefaultValue", a.getP4()); + assertEquals("p5DefaultValue", a.getP5()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + public void testDefaultValuesRead() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Manually create a node + // we need this test as SimpleFieldsHelper.storeSimpleField sets the + // property value if the field is not set but a jcrDefaultValue + // is set. But we want to test, that SimpleFieldsHelper.retrieveSimpleField + // sets the default value from the jcrDefaultValue + // -------------------------------------------------------------------------------- + Node nodeA = ocm.getSession().getRootNode().addNode("testDefault", "ocm:DefTestPrimary"); + nodeA.setProperty("ocm:p1", "p1Value"); + ocm.getSession().save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + Default a = (Default) ocm.getObject( "/testDefault" ); + assertNotNull("a is null", a); + + assertEquals("p1Value", a.getP1()); + assertNull(a.getP2()); + assertEquals("p3DescriptorDefaultValue", a.getP3()); + assertEquals("p4DefaultValue", a.getP4()); + assertEquals("p5DefaultValue", a.getP5()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/atomicconverter/NullAtomicTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterNullAtomicTest.java similarity index 62% rename from src/test/org/apache/portals/graffito/jcr/persistence/atomicconverter/NullAtomicTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterNullAtomicTest.java index 33df0cfd..7952c605 100644 --- a/src/test/org/apache/portals/graffito/jcr/persistence/atomicconverter/NullAtomicTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/DigesterNullAtomicTest.java @@ -1,20 +1,20 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.atomicconverter; +package org.apache.jackrabbit.ocm.manager.atomic; import java.io.ByteArrayInputStream; import java.util.Calendar; @@ -23,110 +23,84 @@ import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.Atomic; +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; /** * Test Atomic perisstence fields * * @author Christophe Lombart */ -public class NullAtomicTest extends TestBase +public class DigesterNullAtomicTest extends DigesterRepositoryTestBase { - private final static Log log = LogFactory.getLog(NullAtomicTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public NullAtomicTest(String testName) - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(NullAtomicTest.class); + return new TestSuite(DigesterNullAtomicTest.class); } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - - super.tearDown(); - } public void testNullValueAtomicFields() { try { - PersistenceManager persistenceManager = getPersistenceManager(); - + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- // Create and store an object graph in the repository // -------------------------------------------------------------------------------- Atomic a = new Atomic(); a.setPath("/test"); - a.setIntegerObject(new Integer(100)); + a.setIntegerObject(new Integer(100)); a.setDate(new Date()); byte[] content = "Test Byte".getBytes(); a.setByteArray(content); a.setCalendar(Calendar.getInstance()); a.setDoubleObject(new Double(2.12)); a.setDoublePrimitive(1.23); - + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream("Test Stream".getBytes()); a.setInputStream(byteArrayInputStream); - - persistenceManager.insert(a); - persistenceManager.save(); - + + ocm.insert(a); + ocm.save(); + // -------------------------------------------------------------------------------- // Get the object // -------------------------------------------------------------------------------- a = null; - a = (Atomic) persistenceManager.getObject(Atomic.class, "/test"); + a = (Atomic) ocm.getObject( "/test"); assertNotNull("a is null", a); assertNull("Boolean object is not null", a.getBooleanObject()); - + assertFalse("Incorrect boolean primitive", a.isBooleanPrimitive()); assertNotNull("Integer Object is null", a.getIntegerObject()); assertTrue("Incorrect Integer object", a.getIntegerObject().intValue() == 100); assertTrue("Incorrect int primitive", a.getIntPrimitive() == 0); - assertNull("String object is not null", a.getString()); + assertNull("String object is not null", a.getString()); assertNotNull("Byte array object is null", a.getByteArray()); assertTrue("Incorrect byte object", new String(a.getByteArray()).equals("Test Byte")); - + assertNotNull("date object is null", a.getDate()); assertNotNull("calendar object is null", a.getCalendar()); - + assertNotNull("Double object is null", a.getDoubleObject()); assertTrue("Incorrect double object", a.getDoubleObject().doubleValue() == 2.12); assertTrue("Incorrect double primitive", a.getDoublePrimitive() == 1.23); - + assertNotNull("Incorrect input stream primitive", a.getInputStream()); - - + + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + } - + } \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/Int2BooleanTypeConverterImpl.java b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/Int2BooleanTypeConverterImpl.java new file mode 100644 index 00000000..4592dc9c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/atomic/Int2BooleanTypeConverterImpl.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.atomic; + +import javax.jcr.Value; +import javax.jcr.ValueFactory; + +import org.apache.jackrabbit.ocm.exception.IncorrectAtomicTypeException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter; + +/** + * This is a simple converter which convert a boolean field value into a jcr long property (int type is not defined in the jcr spec). + * + * @author Christophe Lombart + * + */ +public class Int2BooleanTypeConverterImpl implements AtomicTypeConverter +{ + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getValue(javax.jcr.ValueFactory, Object) + */ + public Value getValue(ValueFactory valueFactory, Object propValue) + { + if (propValue == null) + { + return null; + } + boolean value = ((Boolean) propValue).booleanValue(); + int jcrValue = 0; + + if (value) + { + jcrValue = 1; + } + return valueFactory.createValue(jcrValue); + } + + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getObject(javax.jcr.Value) + */ + public Object getObject(Value value) + { + try + { + long jcrValue = value.getLong(); + if (jcrValue == 1) + { + return new Boolean(true); + } + else + { + return new Boolean(false); + } + } + catch (Exception e) + { + throw new IncorrectAtomicTypeException("Impossible to convert the value : " + value.toString() , e); + } + } + + /** + * + * @see org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverter#getXPathQueryValue(javax.jcr.ValueFactory, Object) + */ + public String getXPathQueryValue(ValueFactory valueFactory, Object object) + { + + return ((Boolean) object).booleanValue() ? "1" : "0"; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/auto/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/auto/AllTests.java new file mode 100644 index 00000000..cc844ebc --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/auto/AllTests.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.auto; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.auto"); + //$JUnit-BEGIN$ + suite.addTestSuite(DigesterAutoTest.class); + suite.addTestSuite(AnnotationAutoTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/auto/AnnotationAutoTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/auto/AnnotationAutoTest.java new file mode 100644 index 00000000..594f4f3b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/auto/AnnotationAutoTest.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.auto; + +import java.util.ArrayList; +import java.util.List; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.AnnotationMapperImpl; +import org.apache.jackrabbit.ocm.testmodel.auto.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.auto.Content; +import org.apache.jackrabbit.ocm.testmodel.auto.Document; +import org.apache.jackrabbit.ocm.testmodel.auto.Folder; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.CmsObjectImpl; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.ContentImpl; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.FolderImpl; + +/** + * Test autoupdate setting + * + * @author Christophe Lombart + */ +public class AnnotationAutoTest extends AnnotationRepositoryTestBase { + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite( + AnnotationAutoTest.class); + } + + + public void testAuto() { + + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + Folder folder = new FolderImpl(); + folder.setPath("/folder2"); + folder.setName("folder2"); + + Document document = new DocumentImpl(); + document.setPath("/folder2/document4"); + document.setName("document4"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 4".getBytes()); + document.setDocumentStream(documentStream); + + Folder subFolder = new FolderImpl(); + subFolder.setName("subfolder"); + subFolder.setPath("/folder2/subfolder"); + + folder.addChild(document); + folder.addChild(subFolder); + ocm.insert(folder); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + Folder folder2 = (Folder) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,0); // autoRetrieve = false + + //--------------------------------------------------------------------------------------------------------- + // Insert nested objects + //--------------------------------------------------------------------------------------------------------- + ocm.insert(subFolder); + ocm.insert(document); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + folder2 = (Folder) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,0); // autoInsert = false + + //--------------------------------------------------------------------------------------------------------- + // Retrieve children attribute + //--------------------------------------------------------------------------------------------------------- + ocm.retrieveMappedAttribute(folder2, "children"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + folder2.setChildren(null); + ocm.update(folder2); // autoupdate = false for the children attribute. So no update on the children collection + ocm.save(); + //--------------------------------------------------------------------------------------------------------- + // Retrieve children attribute + //--------------------------------------------------------------------------------------------------------- + ocm.retrieveMappedAttribute(folder2, "children"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + + } + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException + { + List classes = new ArrayList(); + + classes.add(CmsObject.class); + classes.add(Content.class); + classes.add(Folder.class); + classes.add(Document.class); + classes.add(CmsObjectImpl.class); + classes.add(ContentImpl.class); + classes.add(FolderImpl.class); + classes.add(DocumentImpl.class); + + Mapper mapper = new AnnotationMapperImpl(classes); + return new ObjectContentManagerImpl(session, mapper); + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/auto/DigesterAutoTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/auto/DigesterAutoTest.java new file mode 100644 index 00000000..63c38b15 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/auto/DigesterAutoTest.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.auto; + +//import javax.jcr.Repository; +//import javax.jcr.UnsupportedRepositoryOperationException; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.testmodel.auto.Document; +import org.apache.jackrabbit.ocm.testmodel.auto.Folder; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.FolderImpl; + +/** + * Test autoupdate setting + * + * @author Christophe Lombart + */ +public class DigesterAutoTest extends DigesterRepositoryTestBase { + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite( + DigesterAutoTest.class); + } + + + public void testAuto() { + + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + Folder folder = new FolderImpl(); + folder.setPath("/folder2"); + folder.setName("folder2"); + + Document document = new DocumentImpl(); + document.setPath("/folder2/document4"); + document.setName("document4"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 4".getBytes()); + document.setDocumentStream(documentStream); + + Folder subFolder = new FolderImpl(); + subFolder.setName("subfolder"); + subFolder.setPath("/folder2/subfolder"); + + folder.addChild(document); + folder.addChild(subFolder); + ocm.insert(folder); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + Folder folder2 = (Folder) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,0); // autoRetrieve = false + + //--------------------------------------------------------------------------------------------------------- + // Insert nested objects + //--------------------------------------------------------------------------------------------------------- + ocm.insert(subFolder); + ocm.insert(document); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + folder2 = (Folder) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,0); // autoRetrieve = false + + //--------------------------------------------------------------------------------------------------------- + // Retrieve children attribute + //--------------------------------------------------------------------------------------------------------- + ocm.retrieveMappedAttribute(folder2, "children"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + folder2.setChildren(null); + ocm.update(folder2); // autoupdate = false for the children attribute. So no update on the children collection + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve children attribute + //--------------------------------------------------------------------------------------------------------- + ocm.retrieveMappedAttribute(folder2, "children"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + + } + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException + { + String[] files = {"./src/test/test-config/jcrmapping-auto.xml"}; + return new ObjectContentManagerImpl(session, files); + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AllTests.java new file mode 100644 index 00000000..3393e901 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AllTests.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.basic"); + //$JUnit-BEGIN$ + suite.addTestSuite(DigesterAvoidRecursiveLoopTest.class); + suite.addTestSuite(DigesterCopyMoveTest.class); + suite.addTestSuite(DigesterRemoveTest.class); + suite.addTestSuite(DigesterSameNameSiblingTest.class); + suite.addTestSuite(DigesterSimpleTest.class); + + suite.addTestSuite(AnnotationAvoidRecursiveLoopTest.class); + suite.addTestSuite(AnnotationCopyMoveTest.class); + suite.addTestSuite(AnnotationRemoveTest.class); + suite.addTestSuite(AnnotationSameNameSiblingTest.class); + suite.addTestSuite(AnnotationSimpleTest.class); + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationAvoidRecursiveLoopTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationAvoidRecursiveLoopTest.java new file mode 100644 index 00000000..dd237b67 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationAvoidRecursiveLoopTest.java @@ -0,0 +1,134 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.AnnotationMapperImpl; +import org.apache.jackrabbit.ocm.testmodel.crossreference.A; +import org.apache.jackrabbit.ocm.testmodel.crossreference.B; + + +/** + * Basic test for ObjectContentManager + * Test when objects are cross referenced + * eg. object 'a' contains a reference to an object 'b' and object 'b' contains a reference to 'a'. + * + * @author classes = new ArrayList(); + classes.add(B.class); + classes.add(A.class); + Mapper mapper = new AnnotationMapperImpl(classes); + return new ObjectContentManagerImpl(session, mapper); + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationCopyMoveTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationCopyMoveTest.java new file mode 100644 index 00000000..d9fc649a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationCopyMoveTest.java @@ -0,0 +1,277 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; + + +/** + * Test Copy & move objects + * + * @author Christophe Lombart + */ +public class AnnotationCopyMoveTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return + new TestSuite(AnnotationCopyMoveTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + + + } + + public void testCopy() + { + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Copy the object + // -------------------------------------------------------------------------------- + ocm.copy("/test", "/test2"); + ocm.save(); + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test2"); + assertNotNull("a is null", a); + assertTrue("Invalid field a1", a.getA1().equals("a1")); + assertTrue("Invalid field b.b1", a.getB().getB1().equals("b1")); + assertTrue("Invalid number of items in field collection", a.getCollection().size() == 3); + + + // -------------------------------------------------------------------------------- + // Check exceptions + // -------------------------------------------------------------------------------- + + try + { + ocm.copy("/incorrectpath", "/test2"); + fail("the copy method accepts an incorrect source path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + try + { + ocm.copy("/test", "incorrectpath"); + fail("the copy method accepts an incorrect destination path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + // -------------------------------------------------------------------------------- + // Remove objects + // -------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.remove("/test2"); + ocm.save(); + + } + + public void testSimpleMove() + { + + try { + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + Atomic atomic = new Atomic(); + atomic.setPath("/source"); + atomic.setString("test atomic"); + ocm.insert(atomic); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Copy the object + // -------------------------------------------------------------------------------- + ocm.move("/source", "/result"); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + atomic = (Atomic) ocm.getObject("/result"); + assertNotNull("atomic is null", atomic); + assertTrue("Invalid field a1", atomic.getString().equals("test atomic")); + + assertFalse("Object with path /source still exists", ocm.objectExists("/source")); + + // -------------------------------------------------------------------------------- + // Check exceptions + // -------------------------------------------------------------------------------- + try + { + ocm.move("/incorrectpath", "/test2"); + fail("the copy method accepts an incorrect source path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + try + { + ocm.move("/test", "incorrectpath"); + fail("the copy method accepts an incorrect destination path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + // -------------------------------------------------------------------------------- + // Remove objects + // -------------------------------------------------------------------------------- + ocm.remove("/result"); + ocm.save(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + + + } + + public void testObjectGraphMove() + { + + try { + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/source"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Copy the object + // -------------------------------------------------------------------------------- + ocm.move("/source", "/result"); + ocm.save(); + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/result"); + assertNotNull("a is null", a); + assertTrue("Invalid field a1", a.getA1().equals("a1")); + assertTrue("Invalid field b.b1", a.getB().getB1().equals("b1")); + assertTrue("Invalid number of items in field collection", a.getCollection().size() == 3); + + assertFalse("Object with path /source still exists", ocm.objectExists("/source")); + + // -------------------------------------------------------------------------------- + // Remove objects + // -------------------------------------------------------------------------------- + ocm.remove("/result"); + ocm.save(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + } + + +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerRemoveTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationRemoveTest.java similarity index 51% rename from src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerRemoveTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationRemoveTest.java index a30e9dc5..fd9f01a7 100644 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerRemoveTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationRemoveTest.java @@ -1,20 +1,20 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.impl; +package org.apache.jackrabbit.ocm.manager.basic; import java.io.ByteArrayInputStream; import java.sql.Timestamp; @@ -25,39 +25,29 @@ import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.Atomic; -import org.apache.portals.graffito.jcr.testmodel.MultiValue; +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; + /** * Test Query on atomic fields * * @author Christophe Lombart */ -public class PersistenceManagerRemoveTest extends TestBase +public class AnnotationRemoveTest extends AnnotationRepositoryTestBase { - private final static Log log = LogFactory.getLog(PersistenceManagerRemoveTest.class); private Date date = new Date(); - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerRemoveTest(String testName) throws Exception - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerRemoveTest.class); + return + new TestSuite(AnnotationRemoveTest.class); } /** @@ -67,24 +57,9 @@ protected void setUp() throws Exception { super.setUp(); this.importData(date); - + } - public void tearDown() throws Exception - { - - for (int i = 1; i <= 10; i++) - { - if (getPersistenceManager().objectExists("/test" + i)) - { - getPersistenceManager().remove("/test" + i); - } - - } - getPersistenceManager().save(); - - super.tearDown(); - } public void testRemove() { @@ -92,24 +67,24 @@ public void testRemove() try { - PersistenceManager persistenceManager = this.getPersistenceManager(); - persistenceManager.remove("/test5"); - persistenceManager.save(); + ObjectContentManager ocm = this.getObjectContentManager(); + ocm.remove("/test5"); + ocm.save(); - assertFalse("Test5 has not been removed", persistenceManager.objectExists("/test5")); + assertFalse("Test5 has not been removed", ocm.objectExists("/test5")); - QueryManager queryManager = this.getQueryManager(); + QueryManager queryManager = getObjectContentManager().getQueryManager(); Filter filter = queryManager.createFilter(Atomic.class); filter.addEqualTo("booleanObject" , new Boolean(false)); Query query = queryManager.createQuery(filter); - persistenceManager.remove(query); - persistenceManager.save(); + ocm.remove(query); + ocm.save(); filter = queryManager.createFilter(Atomic.class); filter.setScope("//"); query = queryManager.createQuery(filter); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects", result.size() == 5); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects", 5, result.size()); } catch (Exception e) @@ -125,7 +100,7 @@ private void importData(Date date) try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); for (int i = 1; i <= 10; i++) { @@ -151,13 +126,13 @@ private void importData(Date date) } else { - a.setByteArray("This is small object stored in a Graffito repository".getBytes()); + a.setByteArray("This is small object stored in the repository".getBytes()); a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); } - persistenceManager.insert(a); + ocm.insert(a); } - persistenceManager.save(); + ocm.save(); } catch (Exception e) diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationSameNameSiblingTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationSameNameSiblingTest.java new file mode 100644 index 00000000..1689d841 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationSameNameSiblingTest.java @@ -0,0 +1,215 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.io.ByteArrayInputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + +/** + * Test Query on atomic fields + * + * @author Christophe Lombart + */ +public class AnnotationSameNameSiblingTest extends AnnotationRepositoryTestBase +{ + private Date date = new Date(); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationSameNameSiblingTest.class); + } + + + public void testSameNameSiblings() + { + + try + { + this.importData(date); + ObjectContentManager ocm = this.getObjectContentManager(); + + // Query all objects + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Atomic.class); + filter.setScope("/"); + Query query = queryManager.createQuery(filter); + Collection result = ocm.getObjects(query); + assertEquals("Incorrect number of objects found", 10, result.size()); + + // Get objects + Atomic atomic = (Atomic) ocm.getObject( "/test[2]"); + assertNotNull("Object /test[2] not found", atomic); + + atomic = (Atomic) ocm.getObject( "/test[10]"); + assertNotNull("Object /test[2] not found", atomic); + + // Update the object + atomic.setString("Modified Test String 10"); + ocm.update(atomic); + ocm.save(); + + // Query on the attribute "string" + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Atomic.class); + filter.addLike("string", "Modified%"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Incorrect number of objects found", result.size() == 1); + + atomic = (Atomic) ocm.getObject(query); + assertNotNull("Object not found", atomic); + assertTrue("Incorrect Object", atomic.getString().equals("Modified Test String 10")); + + // Delete all objects + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Atomic.class); + filter.setScope("/"); + query = queryManager.createQuery(filter) ; + ocm.remove(query); + ocm.save(); + + result = ocm.getObjects(query); + assertTrue("Incorrect number of objects found", result.size() == 0); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + + } + + public void testUnsupportedSameNameSiblings() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + Page page = new Page(); + page.setPath("/page"); + page.setTitle("Page Title"); + ocm.insert(page); + ocm.save(); + + Paragraph p1 = new Paragraph("para1"); + p1.setPath("/page/paragraph"); + ocm.insert(p1); + + Paragraph p2 = new Paragraph("para1"); + p2.setPath("/page/paragraph"); + ocm.insert(p2); + fail(); + + } + catch(Exception e) + { + ocm.remove("/page"); + ocm.save(); + } + } + + + private void importData(Date date) + { + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + + for (int i = 1; i <= 10; i++) + { + Atomic a = new Atomic(); + a.setPath("/test"); + a.setBooleanObject(new Boolean(i%2==0)); + a.setBooleanPrimitive(true); + a.setIntegerObject(new Integer(100 * i)); + a.setIntPrimitive(200 + i); + a.setString("Test String " + i); + a.setDate(date); + Calendar calendar = Calendar.getInstance(); + calendar.set(1976, 4, 20, 15, 40); + a.setCalendar(calendar); + a.setDoubleObject(new Double(2.12 + i)); + a.setDoublePrimitive(1.23 + i); + long now = System.currentTimeMillis(); + a.setTimestamp(new Timestamp(now)); + if ((i % 2) == 0) + { + a.setByteArray("This is small object stored in a JCR repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Test inputstream".getBytes())); + } + else + { + a.setByteArray("This is small object stored in the repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); + } + ocm.insert(a); + if (i==1) + { + assertTrue("Invalid Path" , a.getPath().equals("/test") ); + } + else + { + assertTrue("Invalid Path" , a.getPath().equals("/test" + "[" + i + "]") ); + } + + + } + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException + { + String[] files = { "./src/test/test-config/jcrmapping-sibling.xml" }; + + return new ObjectContentManagerImpl(session, files); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationSimpleTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationSimpleTest.java new file mode 100644 index 00000000..6e440fa5 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/AnnotationSimpleTest.java @@ -0,0 +1,198 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.Discriminator; + +/** + * Test JcrSession + * + * @author Christophe Lombart + */ +public class AnnotationSimpleTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationSimpleTest.class); + } + + + public void testClassA() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertTrue("Incorrect a1", a.getA1().equals("a1")); + assertNotNull("a.b is null", a.getB()); + assertTrue("Incorrect a.b.b1", a.getB().getB1().equals("b1")); + assertNotNull("a.collection is null", a.getCollection()); + assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setA1("new value"); + B newB = new B(); + newB.setB1("new B1"); + newB.setB2("new B2"); + a.setB(newB); + + + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test"); + assertNotNull("a is null", a); + assertTrue("Incorrect a1", a.getA1().equals("new value")); + assertNotNull("a.b is null", a.getB()); + assertTrue("Incorrect a.b.b1", a.getB().getB1().equals("new B1")); + + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Test an persistent object mapped with a discriminator and with a nodetype + * + */ + public void testDiscriminatorAndNodeType() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store the object in the repository + // -------------------------------------------------------------------------------- + Discriminator discriminatorObject = new Discriminator(); + discriminatorObject.setPath("/test"); + discriminatorObject.setContent("This is my content"); + ocm.insert(discriminatorObject); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + discriminatorObject = (Discriminator) ocm.getObject( "/test"); + assertNotNull("discriminator object is null", discriminatorObject ); + assertTrue("Incorrect content", discriminatorObject.getContent().equals("This is my content")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + discriminatorObject.setContent("new content"); + + ocm.update(discriminatorObject); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + discriminatorObject = (Discriminator) ocm.getObject( "/test"); + assertNotNull("discriminator object is null", discriminatorObject ); + assertTrue("Incorrect content", discriminatorObject.getContent().equals("new content")); + + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } + + public void testIsPersistent() + { + ObjectContentManager ocm = getObjectContentManager(); + assertTrue("Class A is not persistent ", ocm.isPersistent(A.class)); + assertFalse("Class SomeRandomUnMappedType is persistent - hum ? ", ocm.isPersistent(SomeRandomUnMappedType.class)); + + } + + +} +class SomeRandomUnMappedType{ + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterAvoidRecursiveLoopTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterAvoidRecursiveLoopTest.java new file mode 100644 index 00000000..4746156c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterAvoidRecursiveLoopTest.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.util.Collection; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.testmodel.crossreference.A; +import org.apache.jackrabbit.ocm.testmodel.crossreference.B; + + +/** + * Basic test for ObjectContentManager + * Test when objects are cross referenced + * eg. object 'a' contains a reference to an object 'b' and object 'b' contains a reference to 'a'. + * + * @author Christophe Lombart + */ +public class DigesterCopyMoveTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return + new TestSuite(DigesterCopyMoveTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + + + } + + public void testCopy() + { + + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Copy the object + // -------------------------------------------------------------------------------- + ocm.copy("/test", "/test2"); + ocm.save(); + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test2"); + assertNotNull("a is null", a); + assertTrue("Invalid field a1", a.getA1().equals("a1")); + assertTrue("Invalid field b.b1", a.getB().getB1().equals("b1")); + assertTrue("Invalid number of items in field collection", a.getCollection().size() == 3); + + + // -------------------------------------------------------------------------------- + // Check exceptions + // -------------------------------------------------------------------------------- + + try + { + ocm.copy("/incorrectpath", "/test2"); + fail("the copy method accepts an incorrect source path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + try + { + ocm.copy("/test", "incorrectpath"); + fail("the copy method accepts an incorrect destination path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + // -------------------------------------------------------------------------------- + // Remove objects + // -------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.remove("/test2"); + ocm.save(); + + } + + public void testSimpleMove() + { + + try { + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + Atomic atomic = new Atomic(); + atomic.setPath("/source"); + atomic.setString("test atomic"); + ocm.insert(atomic); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Copy the object + // -------------------------------------------------------------------------------- + ocm.move("/source", "/result"); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + atomic = (Atomic) ocm.getObject("/result"); + assertNotNull("atomic is null", atomic); + assertTrue("Invalid field a1", atomic.getString().equals("test atomic")); + + assertFalse("Object with path /source still exists", ocm.objectExists("/source")); + + // -------------------------------------------------------------------------------- + // Check exceptions + // -------------------------------------------------------------------------------- + try + { + ocm.move("/incorrectpath", "/test2"); + fail("the copy method accepts an incorrect source path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + try + { + ocm.move("/test", "incorrectpath"); + + fail("the copy method accepts an incorrect destination path"); + } catch (ObjectContentManagerException e) + { + // Nothing to do - Expected behaviour + } + + // -------------------------------------------------------------------------------- + // Remove objects + // -------------------------------------------------------------------------------- + ocm.remove("/result"); + ocm.save(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + + + } + + public void testObjectGraphMove() + { + + try { + ObjectContentManager ocm = getObjectContentManager(); + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/source"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Move the object + // -------------------------------------------------------------------------------- + ocm.move("/source", "/result"); + //session = RepositoryUtil.login(repository, "superuser", "superuser"); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/result"); + assertNotNull("a is null", a); + assertTrue("Invalid field a1", a.getA1().equals("a1")); + assertTrue("Invalid field b.b1", a.getB().getB1().equals("b1")); + assertTrue("Invalid number of items in field collection", a.getCollection().size() == 3); + + assertFalse("Object with path /source still exists", ocm.objectExists("/source")); + + // -------------------------------------------------------------------------------- + // Remove objects + // -------------------------------------------------------------------------------- + ocm.remove("/result"); + ocm.save(); + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterRemoveTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterRemoveTest.java new file mode 100644 index 00000000..82519e02 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterRemoveTest.java @@ -0,0 +1,145 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.io.ByteArrayInputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; + + +/** + * Test Query on atomic fields + * + * @author Christophe Lombart + */ +public class DigesterRemoveTest extends DigesterRepositoryTestBase +{ + private Date date = new Date(); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return + new TestSuite(DigesterRemoveTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + this.importData(date); + + } + + + public void testRemove() + { + + try + { + + ObjectContentManager ocm = getObjectContentManager(); + ocm.remove("/test5"); + ocm.save(); + + assertFalse("Test5 has not been removed", ocm.objectExists("/test5")); + + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Atomic.class); + filter.addEqualTo("booleanObject" , new Boolean(false)); + Query query = queryManager.createQuery(filter); + ocm.remove(query); + ocm.save(); + + filter = queryManager.createFilter(Atomic.class); + filter.setScope("//"); + query = queryManager.createQuery(filter); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects", 5, result.size()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + + } + + private void importData(Date date) + { + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + for (int i = 1; i <= 10; i++) + { + Atomic a = new Atomic(); + a.setPath("/test" + i); + a.setBooleanObject(new Boolean(i % 2 == 0)); + a.setBooleanPrimitive(true); + a.setIntegerObject(new Integer(100 * i)); + a.setIntPrimitive(200 + i); + a.setString("Test String " + i); + a.setDate(date); + Calendar calendar = Calendar.getInstance(); + calendar.set(1976, 4, 20, 15, 40); + a.setCalendar(calendar); + a.setDoubleObject(new Double(2.12 + i)); + a.setDoublePrimitive(1.23 + i); + long now = System.currentTimeMillis(); + a.setTimestamp(new Timestamp(now)); + if ((i % 2) == 0) + { + a.setByteArray("This is small object stored in a JCR repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Test inputstream".getBytes())); + } + else + { + a.setByteArray("This is small object stored in the repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); + } + ocm.insert(a); + + } + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterSameNameSiblingTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterSameNameSiblingTest.java new file mode 100644 index 00000000..c88c5cae --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterSameNameSiblingTest.java @@ -0,0 +1,216 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.io.ByteArrayInputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; + +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.UnsupportedRepositoryOperationException; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + +/** + * Test Query on atomic fields + * + * @author Christophe Lombart + */ +public class DigesterSameNameSiblingTest extends DigesterRepositoryTestBase +{ + private Date date = new Date(); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterSameNameSiblingTest.class); + } + + public void testSameNameSiblings() + { + + try + { + this.importData(date); + ObjectContentManager ocm = getObjectContentManager(); + + // Query all objects + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Atomic.class); + filter.setScope("/"); + Query query = queryManager.createQuery(filter); + Collection result = ocm.getObjects(query); + assertEquals("Incorrect number of objects found", 10, result.size()); + + // Get objects + Atomic atomic = (Atomic) ocm.getObject( "/test[2]"); + assertNotNull("Object /test[2] not found", atomic); + + atomic = (Atomic) ocm.getObject( "/test[10]"); + assertNotNull("Object /test[2] not found", atomic); + + // Update the object + atomic.setString("Modified Test String 10"); + ocm.update(atomic); + ocm.save(); + + // Query on the attribute "string" + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Atomic.class); + filter.addLike("string", "Modified%"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Incorrect number of objects found", result.size() == 1); + + atomic = (Atomic) ocm.getObject(query); + assertNotNull("Object not found", atomic); + assertTrue("Incorrect Object", atomic.getString().equals("Modified Test String 10")); + + // Delete all objects + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Atomic.class); + filter.setScope("/"); + query = queryManager.createQuery(filter) ; + ocm.remove(query); + ocm.save(); + + result = ocm.getObjects(query); + assertTrue("Incorrect number of objects found", result.size() == 0); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + + } + + public void testUnsupportedSameNameSiblings() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + Page page = new Page(); + page.setPath("/page"); + page.setTitle("Page Title"); + ocm.insert(page); + ocm.save(); + + Paragraph p1 = new Paragraph("para1"); + p1.setPath("/page/paragraph"); + ocm.insert(p1); + + Paragraph p2 = new Paragraph("para1"); + p2.setPath("/page/paragraph"); + ocm.insert(p2); + fail(); + + } + catch(Exception e) + { + ocm.remove("/page"); + ocm.save(); + } + } + + + private void importData(Date date) + { + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + + for (int i = 1; i <= 10; i++) + { + Atomic a = new Atomic(); + a.setPath("/test"); + a.setBooleanObject(new Boolean(i%2==0)); + a.setBooleanPrimitive(true); + a.setIntegerObject(new Integer(100 * i)); + a.setIntPrimitive(200 + i); + a.setString("Test String " + i); + a.setDate(date); + Calendar calendar = Calendar.getInstance(); + calendar.set(1976, 4, 20, 15, 40); + a.setCalendar(calendar); + a.setDoubleObject(new Double(2.12 + i)); + a.setDoublePrimitive(1.23 + i); + long now = System.currentTimeMillis(); + a.setTimestamp(new Timestamp(now)); + if ((i % 2) == 0) + { + a.setByteArray("This is small object stored in a JCR repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Test inputstream".getBytes())); + } + else + { + a.setByteArray("This is small object stored in the repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); + } + ocm.insert(a); + if (i==1) + { + assertTrue("Invalid Path" , a.getPath().equals("/test") ); + } + else + { + assertTrue("Invalid Path" , a.getPath().equals("/test" + "[" + i + "]") ); + } + + + } + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException + { + String[] files = { "./src/test/test-config/jcrmapping-sibling.xml" }; + + return new ObjectContentManagerImpl(session, files); + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterSimpleTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterSimpleTest.java new file mode 100644 index 00000000..853b395c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/basic/DigesterSimpleTest.java @@ -0,0 +1,195 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.basic; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.Discriminator; + +/** + * Test JcrSession + * + * @author Christophe Lombart + */ +public class DigesterSimpleTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterSimpleTest.class); + } + + + public void testClassA() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertTrue("Incorrect a1", a.getA1().equals("a1")); + assertNotNull("a.b is null", a.getB()); + assertTrue("Incorrect a.b.b1", a.getB().getB1().equals("b1")); + assertNotNull("a.collection is null", a.getCollection()); + assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setA1("new value"); + B newB = new B(); + newB.setB1("new B1"); + newB.setB2("new B2"); + a.setB(newB); + + + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test"); + assertNotNull("a is null", a); + assertTrue("Incorrect a1", a.getA1().equals("new value")); + assertNotNull("a.b is null", a.getB()); + assertTrue("Incorrect a.b.b1", a.getB().getB1().equals("new B1")); + + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Test an persistent object mapped with a discriminator and with a nodetype + * + */ + public void testDiscriminatorAndNodeType() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store the object in the repository + // -------------------------------------------------------------------------------- + Discriminator discriminatorObject = new Discriminator(); + discriminatorObject.setPath("/test"); + discriminatorObject.setContent("This is my content"); + ocm.insert(discriminatorObject); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + discriminatorObject = (Discriminator) ocm.getObject( "/test"); + assertNotNull("discriminator object is null", discriminatorObject ); + assertTrue("Incorrect content", discriminatorObject.getContent().equals("This is my content")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + discriminatorObject.setContent("new content"); + + ocm.update(discriminatorObject); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + discriminatorObject = (Discriminator) ocm.getObject( "/test"); + assertNotNull("discriminator object is null", discriminatorObject ); + assertTrue("Incorrect content", discriminatorObject.getContent().equals("new content")); + + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } + + public void testIsPersistent() + { + ObjectContentManager ocm = getObjectContentManager(); + assertTrue("Class A is not persistent ", ocm.isPersistent(A.class)); + assertFalse("Class SomeRandomUnMappedDigesterType is persistent - hum ? ", ocm.isPersistent(SomeRandomUnMappedDigesterType.class)); + } +} +class SomeRandomUnMappedDigesterType{ + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/AllTests.java new file mode 100644 index 00000000..71103b6f --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/AllTests.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.beanconverter"); + //$JUnit-BEGIN$ + suite.addTestSuite(DigesterBeanDescriptorTest.class); + suite.addTestSuite(AnnotationBeanDescriptorTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/AnnotationBeanDescriptorTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/AnnotationBeanDescriptorTest.java new file mode 100644 index 00000000..04c52e56 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/AnnotationBeanDescriptorTest.java @@ -0,0 +1,286 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter; + + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.D; +import org.apache.jackrabbit.ocm.testmodel.DFull; +import org.apache.jackrabbit.ocm.testmodel.E; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ObjectConverter test for bean-descriptor with inner bean inlined and inner bean with + * custom converter. + * + * @author Alexandru Popescu + */ +public class AnnotationBeanDescriptorTest extends AnnotationRepositoryTestBase { + + private final static Logger log = LoggerFactory.getLogger(AnnotationBeanDescriptorTest.class); + + + public static Test suite() { + + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationBeanDescriptorTest.class); + } + + + /** + * @see org.apache.jackrabbit.ocm.DigesterTestBase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + public void tearDown() throws Exception + { + FakeBeanConverter.cleanUpLog(); + cleanUpRepisotory(); + super.tearDown(); + } + public void testBasic() throws Exception + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + // ------------------------------------------------------------------------ + // Create a main object (a) with a null attribute (A.b) + // ------------------------------------------------------------------------ + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + ocm.insert(a); + ocm.save(); + + // ------------------------------------------------------------------------ + // Retrieve + // ------------------------------------------------------------------------ + a = (A) ocm.getObject("/test"); + assertNotNull("Object is null", a); + assertNull("attribute is not null", a.getB()); + + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + ocm.update(a); + ocm.save(); + + // ------------------------------------------------------------------------ + // Retrieve + // ------------------------------------------------------------------------ + a = (A) ocm.getObject("/test"); + assertNotNull("Object is null", a); + assertNotNull("attribute is null", a.getB()); + + // ------------------------------------------------------------------------ + // Remove object + // ------------------------------------------------------------------------ + ocm.remove("/test"); + ocm.save(); + } + catch (RuntimeException e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + + } + public void testInlined() throws Exception { + + ObjectContentManager ocm = getObjectContentManager(); + B expB = new B(); + expB.setB1("b1value"); + expB.setB2("b2value"); + D expD = new D(); + expD.setPath("/someD"); + expD.setD1("d1value"); + expD.setB1(expB); + + ocm.insert( expD); + ocm.save(); + + D actD = (D) ocm.getObject( "/someD"); + + assertEquals(expD.getD1(), actD.getD1()); + assertEquals(expB.getB1(), actD.getB1().getB1()); + assertEquals(expB.getB2(), actD.getB1().getB2()); + + DFull actDFull = (DFull) ocm.getObject( DFull.class, "/someD"); + + assertEquals(expD.getD1(), actDFull.getD1()); + assertEquals(expB.getB1(), actDFull.getB1()); + assertEquals(expB.getB2(), actDFull.getB2()); + + expB.setB1("updatedvalue1"); + + ocm.update( expD); + getSession().save(); + + actD = (D) ocm.getObject( "/someD"); + + assertEquals(expD.getD1(), actD.getD1()); + assertEquals(expB.getB1(), actD.getB1().getB1()); + assertEquals(expB.getB2(), actD.getB1().getB2()); + + actDFull = (DFull) ocm.getObject( DFull.class, "/someD"); + + assertEquals(expD.getD1(), actDFull.getD1()); + assertEquals(expB.getB1(), actDFull.getB1()); + assertEquals(expB.getB2(), actDFull.getB2()); + + + expD.setB1(null); + ocm.update( expD); + getSession().save(); + + actD = (D) ocm.getObject( "/someD"); + + assertEquals(expD.getD1(), actD.getD1()); + assertNull("b1 was not removed", actD.getB1()); + + actDFull = (DFull) ocm.getObject( DFull.class, "/someD"); + assertEquals(expD.getD1(), actDFull.getD1()); + assertNull("b1 was not removed", actDFull.getB1()); + assertNull("b2 wan not remove", actDFull.getB2()); + + } + + + public void testBeanDescriptorConverter() throws Exception + { + + ObjectContentManager ocm = getObjectContentManager(); + B expB = new B(); + expB.setB1("b1value"); + expB.setB2("b2value"); + E expE = new E(); + expE.setPath("/someD"); + expE.setD1("d1value"); + expE.setB1(expB); + + + ocm.insert( expE); + ocm.save(); + + E actE = (E) ocm.getObject( "/someD"); + + assertEquals(expE.getD1(), actE.getD1()); + + expE.setD1("updatedvalueD1"); + expB.setB1("updatedvalue1"); + + ocm.update( expE); + ocm.save(); + + actE = (E) ocm.getObject( "/someD"); + + assertEquals(expE.getD1(), actE.getD1()); + + expE.setB1(null); + ocm.update( expE); + ocm.save(); + + actE = (E) ocm.getObject( "/someD"); + + assertEquals(expE.getD1(), actE.getD1()); + + + List messages = FakeBeanConverter.getLog(); + assertEquals(6, messages.size()); + assertEquals("insert at path /someD", messages.get(0)); + assertEquals("get from path /someD", messages.get(1)); + assertEquals("update at path /someD", messages.get(2)); + assertEquals("get from path /someD", messages.get(3)); + assertEquals("remove from path /someD", messages.get(4)); + assertEquals("get from path /someD", messages.get(5)); + + } + + public void testParentBeanConverter() throws Exception + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + Page page = new Page(); + page.setPath("/test"); + page.setTitle("Page Title"); + + List paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + page = (Page) ocm.getObject("/test"); + paragraphs = page.getParagraphs(); + for (Paragraph paragraph : paragraphs) { + log.info("Paragraph path : " + paragraph.getPath()); + } + Paragraph p1 = (Paragraph) ocm.getObject("/test/paragraph[2]"); + Page paraPage = p1.getPage(); + assertNotNull("Parent page is null", paraPage); + assertTrue("Invalid parent page", paraPage.getPath().equals("/test")); + + // -------------------------------------------------------------------------------- + // Remove the object + // -------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/DigesterBeanDescriptorTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/DigesterBeanDescriptorTest.java new file mode 100644 index 00000000..3219aedd --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/DigesterBeanDescriptorTest.java @@ -0,0 +1,287 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter; + + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.D; +import org.apache.jackrabbit.ocm.testmodel.DFull; +import org.apache.jackrabbit.ocm.testmodel.E; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ObjectConverter test for bean-descriptor with inner bean inlined and inner bean with + * custom converter. + * + * @author Alexandru Popescu + */ +public class DigesterBeanDescriptorTest extends DigesterRepositoryTestBase { + + + private final static Logger log = LoggerFactory.getLogger(DigesterBeanDescriptorTest.class); + + public static Test suite() { + + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterBeanDescriptorTest.class); + } + + + /** + * @see org.apache.jackrabbit.ocm.DigesterTestBase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + public void tearDown() throws Exception + { + FakeBeanConverter.cleanUpLog(); + cleanUpRepisotory(); + super.tearDown(); + } + + public void testBasic() throws Exception + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + // ------------------------------------------------------------------------ + // Create a main object (a) with a null attribute (A.b) + // ------------------------------------------------------------------------ + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + ocm.insert(a); + ocm.save(); + + // ------------------------------------------------------------------------ + // Retrieve + // ------------------------------------------------------------------------ + a = (A) ocm.getObject("/test"); + assertNotNull("Object is null", a); + assertNull("attribute is not null", a.getB()); + + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + ocm.update(a); + ocm.save(); + + // ------------------------------------------------------------------------ + // Retrieve + // ------------------------------------------------------------------------ + a = (A) ocm.getObject("/test"); + assertNotNull("Object is null", a); + assertNotNull("attribute is null", a.getB()); + + // ------------------------------------------------------------------------ + // Remove object + // ------------------------------------------------------------------------ + ocm.remove("/test"); + ocm.save(); + } + catch (RuntimeException e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + + } + public void testInlined() throws Exception { + + ObjectContentManager ocm = getObjectContentManager(); + B expB = new B(); + expB.setB1("b1value"); + expB.setB2("b2value"); + D expD = new D(); + expD.setPath("/someD"); + expD.setD1("d1value"); + expD.setB1(expB); + + ocm.insert( expD); + ocm.save(); + + D actD = (D) ocm.getObject( "/someD"); + + assertEquals(expD.getD1(), actD.getD1()); + assertEquals(expB.getB1(), actD.getB1().getB1()); + assertEquals(expB.getB2(), actD.getB1().getB2()); + + DFull actDFull = (DFull) ocm.getObject( DFull.class, "/someD"); + + assertEquals(expD.getD1(), actDFull.getD1()); + assertEquals(expB.getB1(), actDFull.getB1()); + assertEquals(expB.getB2(), actDFull.getB2()); + + expB.setB1("updatedvalue1"); + + ocm.update( expD); + getSession().save(); + + actD = (D) ocm.getObject( "/someD"); + + assertEquals(expD.getD1(), actD.getD1()); + assertEquals(expB.getB1(), actD.getB1().getB1()); + assertEquals(expB.getB2(), actD.getB1().getB2()); + + actDFull = (DFull) ocm.getObject( DFull.class, "/someD"); + + assertEquals(expD.getD1(), actDFull.getD1()); + assertEquals(expB.getB1(), actDFull.getB1()); + assertEquals(expB.getB2(), actDFull.getB2()); + + + expD.setB1(null); + ocm.update( expD); + getSession().save(); + + actD = (D) ocm.getObject( "/someD"); + + assertEquals(expD.getD1(), actD.getD1()); + assertNull("b1 was not removed", actD.getB1()); + + actDFull = (DFull) ocm.getObject( DFull.class, "/someD"); + assertEquals(expD.getD1(), actDFull.getD1()); + assertNull("b1 was not removed", actDFull.getB1()); + assertNull("b2 wan not remove", actDFull.getB2()); + + } + + + public void testBeanDescriptorConverter() throws Exception + { + + ObjectContentManager ocm = getObjectContentManager(); + B expB = new B(); + expB.setB1("b1value"); + expB.setB2("b2value"); + E expE = new E(); + expE.setPath("/someD"); + expE.setD1("d1value"); + expE.setB1(expB); + + + ocm.insert( expE); + ocm.save(); + + E actE = (E) ocm.getObject( "/someD"); + + assertEquals(expE.getD1(), actE.getD1()); + + expE.setD1("updatedvalueD1"); + expB.setB1("updatedvalue1"); + + ocm.update( expE); + ocm.save(); + + actE = (E) ocm.getObject( "/someD"); + + assertEquals(expE.getD1(), actE.getD1()); + + expE.setB1(null); + ocm.update( expE); + ocm.save(); + + actE = (E) ocm.getObject( "/someD"); + + assertEquals(expE.getD1(), actE.getD1()); + + + List messages = FakeBeanConverter.getLog(); + assertEquals(6, messages.size()); + assertEquals("insert at path /someD", messages.get(0)); + assertEquals("get from path /someD", messages.get(1)); + assertEquals("update at path /someD", messages.get(2)); + assertEquals("get from path /someD", messages.get(3)); + assertEquals("remove from path /someD", messages.get(4)); + assertEquals("get from path /someD", messages.get(5)); + + } + + public void testParentBeanConverter() throws Exception + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + Page page = new Page(); + page.setPath("/test"); + page.setTitle("Page Title"); + + List paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + page = (Page) ocm.getObject("/test"); + paragraphs = page.getParagraphs(); + for (Paragraph paragraph : paragraphs) { + log.info("Paragraph path : " + paragraph.getPath()); + } + Paragraph p1 = (Paragraph) ocm.getObject("/test/paragraph[2]"); + Page paraPage = p1.getPage(); + assertNotNull("Parent page is null", paraPage); + assertTrue("Invalid parent page", paraPage.getPath().equals("/test")); + + // -------------------------------------------------------------------------------- + // Remove the object + // -------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/FakeBeanConverter.java b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/FakeBeanConverter.java new file mode 100644 index 00000000..e13d07ab --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/beanconverter/FakeBeanConverter.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.beanconverter; + +import java.util.ArrayList; +import java.util.List; + +import javax.jcr.Node; +import javax.jcr.Session; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.exception.ObjectContentManagerException; +import org.apache.jackrabbit.ocm.exception.RepositoryException; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.AtomicTypeConverterProvider; +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.AbstractBeanConverterImpl; +import org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter; +import org.apache.jackrabbit.ocm.mapper.Mapper; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.testmodel.B; + +public class FakeBeanConverter extends AbstractBeanConverterImpl implements BeanConverter { + + private static List log = new ArrayList(); + + public FakeBeanConverter(Mapper mapper, ObjectConverter objectConverter, AtomicTypeConverterProvider atomicTypeConverterProvider) { + super(mapper, objectConverter, atomicTypeConverterProvider); + + + } + + public static void cleanUpLog() { + log.clear(); + } + + public static List getLog() { + return log; + } + + public void insert(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + try { + log.add("insert at path " + parentNode.getPath()); + + } catch (javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException(re); + } + } + + public void update(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + try { + log.add("update at path " + parentNode.getPath()); + } + catch(javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException(re); + } + + } + + public Object getObject(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Class beanClass, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + try { + log.add("get from path " + parentNode.getPath()); + } catch (javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException(re); + } + // The B object is not important for the unit test. + // The unit test checks only the log generated by this converter + return new B(); + } + + public void remove(Session session, Node parentNode, BeanDescriptor beanDescriptor, ClassDescriptor beanClassDescriptor, Object object, ClassDescriptor parentClassDescriptor, Object parent) + throws ObjectContentManagerException, RepositoryException, JcrMappingException { + + try { + log.add("remove from path " + parentNode.getPath()); + } catch (javax.jcr.RepositoryException re) { + throw new ObjectContentManagerException(re); + } + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AllTests.java new file mode 100644 index 00000000..05cc9128 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AllTests.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.collectionconverter"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationArrayListTest.class); + suite.addTestSuite(AnnotationDefaultCollectionConverterImplTest.class); + suite.addTestSuite(AnnotationHashMapTest.class); + suite.addTestSuite(AnnotationMultiValueCollectionConverterImplTest.class); + suite.addTestSuite(AnnotationNTCollectionConverterImplTest.class); + suite.addTestSuite(AnnotationPersonListTest.class); + suite.addTestSuite(AnnotationResidualNodesCollectionConverterImplTest.class); + suite.addTestSuite(AnnotationResidualPropertiesCollectionConverterImplTest.class); + suite.addTestSuite(DigesterArrayListTest.class); + suite.addTestSuite(DigesterDefaultCollectionConverterImplTest.class); + suite.addTestSuite(DigesterHashMapTest.class); + suite.addTestSuite(DigesterMultiValueCollectionConverterImplTest.class); + suite.addTestSuite(DigesterNTCollectionConverterImplTest.class); + suite.addTestSuite(DigesterPersonListTest.class); + suite.addTestSuite(DigesterResidualNodesCollectionConverterImplTest.class); + suite.addTestSuite(DigesterResidualPropertiesCollectionConverterImplTest.class); + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationArrayListTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationArrayListTest.java new file mode 100644 index 00000000..0670caaa --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationArrayListTest.java @@ -0,0 +1,179 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.ArrayListElement; +import org.apache.jackrabbit.ocm.testmodel.collection.CustomList; +import org.apache.jackrabbit.ocm.testmodel.collection.Element; +import org.apache.jackrabbit.ocm.testmodel.collection.Main; + +/** + * @author Christophe Lombart + */ +public class AnnotationArrayListTest extends AnnotationRepositoryTestBase +{ + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationArrayListTest.class); + } + + + public void testArrayList() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // with a null value for the arraylist + // -------------------------------------------------------------------------------- + + Main main = new Main(); + main.setPath("/test"); + main.setText("Main text"); + + ocm.insert(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + ArrayListElement arrayListElement = main.getArrayListElement(); + List list = main.getList(); + CustomList customList = main.getCustomList(); + + assertNull("main.getArrayListElement is not null", arrayListElement ); + assertNull("main.getList is not null", list ); + assertNull("main.getCustomList is not null", customList ); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + + arrayListElement = new ArrayListElement(); + list = new ArrayList(); + customList = new CustomList(); + + Element e1 = new Element(); + e1.setId("e1"); + e1.setText("Element 1"); + arrayListElement.addObject(e1); + list.add(e1); + customList.add(e1); + + Element e2 = new Element(); + e2.setId("e2"); + e2.setText("Element 2"); + arrayListElement.addObject(e2); + list.add(e2); + customList.add(e2); + + main.setArrayListElement(arrayListElement); + main.setList(list); + main.setCustomList(customList); + + ocm.update(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + arrayListElement = main.getArrayListElement(); + list = main.getList(); + assertNotNull("main.getArrayListElemnt is null", arrayListElement ); + assertNotNull("main.getList is null", list ); + assertNotNull("main.getCustomeList is null", customList ); + Collection objects = (Collection) arrayListElement.getObjects(); + Element[] elements = (Element[]) objects.toArray(new Element[objects.size()]); + assertTrue("Incorrect para element", elements[0].getText().equals("Element 1")); + assertTrue("Incorrect para element", list.get(0).getText().equals("Element 1")); + assertTrue("Incorrect para element", customList.get(0).getText().equals("Element 1")); + + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + arrayListElement = new ArrayListElement(); + list = new ArrayList(); + customList = new CustomList(); + + e1 = new Element(); + e1.setId("e1"); + e1.setText("Element 1"); + arrayListElement.addObject(e1); + list.add(e1); + customList.add(e1); + + e2 = new Element(); + e2.setId("e3"); + e2.setText("Element 3"); + arrayListElement.addObject(e2); + list.add(e2); + customList.add(e2); + + Element e3 = new Element(); + e3.setId("e4"); + e3.setText("Element 4"); + arrayListElement.addObject(e3); + list.add(e3); + customList.add(e3); + + main.setArrayListElement(arrayListElement); + main.setList(list); + main.setCustomList(customList); + + ocm.update(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + arrayListElement = main.getArrayListElement(); + list = main.getList(); + assertNotNull("main.getArrayListElement() is null", arrayListElement ); + assertNotNull("main.getList() is null", list ); + objects = (Collection) arrayListElement.getObjects(); + elements = (Element[]) objects.toArray(new Element[objects.size()]); + assertTrue("Incorrect element", elements[2].getText().equals("Element 4")); + assertTrue("Incorrect element", list.get(2).getText().equals("Element 4")); + assertTrue("Incorrect element", customList.get(2).getText().equals("Element 4")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationDefaultCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationDefaultCollectionConverterImplTest.java new file mode 100644 index 00000000..f83482f5 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationDefaultCollectionConverterImplTest.java @@ -0,0 +1,287 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.C; + +/** + * Test DefaultCollectionConverterImpl + * + * @author Christophe Lombart + */ +public class AnnotationDefaultCollectionConverterImplTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationDefaultCollectionConverterImplTest.class); + } + + + public void testNull() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object with a null collection field + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNull("a.collection is not null", a.getCollection()); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test"); + assertNotNull("a is null", a); + assertNotNull("a.collection is null", a.getCollection()); + assertTrue("Incorrect collection size", a.getCollection().size() == 3); + assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setCollection(null); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNull("a.collection is not null", a.getCollection()); + + // -------------------------------------------------------------------------------- + // Export to check the content + // -------------------------------------------------------------------------------- + this.exportDocument("target/DefaultCollectionConverterExport.xml", "/test", true, false); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + public void testDropElement() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a.collection is null", a.getCollection()); + assertEquals("Incorrect a.collection size", 3, a.getCollection().size()); + assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + c1 = new C(); + c1.setId("new first"); + c1.setName("First Element"); + + c2 = new C(); + c2.setId("new second"); + c2.setName("Second Element"); + + collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + a.setCollection(collection); + + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertNotNull("a.collection is null", a.getCollection()); + assertTrue("Incorrect collection size", a.getCollection().size() == 2); + assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("new first")); + + // -------------------------------------------------------------------------------- + // Export to check the content + // -------------------------------------------------------------------------------- + this.exportDocument("target/DefaultCollectionConverterExport.xml", "/test", true, false); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + public void testAddElement() + { + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a.collection is null", a.getCollection()); + assertEquals("Incorrect a.collection size", 3, a.getCollection().size()); + assertEquals("Incorrect a.collection", "first", ((C) a.getCollection().iterator().next()).getId()); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + C c4 = new C(); + c4.setId("Fourth"); + c4.setName("Fourth Element"); + + collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + collection.add(c4); + a.setCollection(collection); + + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + assertNotNull("a.collection is null", a.getCollection()); + assertEquals("Incorrect collection size", 4, a.getCollection().size()); + assertEquals("Incorrect a.collection", "first", ((C) a.getCollection().iterator().next()).getId()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationHashMapTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationHashMapTest.java new file mode 100644 index 00000000..321f167c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationHashMapTest.java @@ -0,0 +1,167 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.HashMap; +import java.util.Map; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.Element; +import org.apache.jackrabbit.ocm.testmodel.collection.HashMapElement; +import org.apache.jackrabbit.ocm.testmodel.collection.Main; + +/** + * Test NTCollectionConverterImpl + * + * @author Christophe Lombart + */ +public class AnnotationHashMapTest extends AnnotationRepositoryTestBase +{ + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationHashMapTest.class); + } + + + public void testHashMap() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with null hashmap + // -------------------------------------------------------------------------------- + + Main main = new Main(); + main.setPath("/test"); + main.setText("Main text"); + + ocm.insert(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertTrue("Incorrect text", main.getText().equals("Main text")); + assertNull("HashMap is not null", main.getHashMapElement()); + assertNull("Map is not null", main.getMap()); + + // -------------------------------------------------------------------------------- + // Update an object graph in the repository + // -------------------------------------------------------------------------------- + + main = new Main(); + main.setPath("/test"); + main.setText("Main text"); + + HashMapElement hashMapElement = new HashMapElement(); + Map map = new HashMap(); + + Element e1 = new Element(); + e1.setId("e1"); + e1.setText("Element 1"); + hashMapElement.addObject(e1); + map.put("keyE1", e1); + + Element e2 = new Element(); + e2.setId("e2"); + e2.setText("Element 2"); + hashMapElement.addObject(e2); + map.put("keyE2", e2); + + main.setHashMapElement(hashMapElement); + main.setMap(map); + + ocm.update(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("main.getHashMap() is null", main.getHashMapElement()); + assertNotNull("main.getHashMap() is null", main.getMap()); + assertTrue("Incorrect text", main.getText().equals("Main text")); + map = (Map) main.getHashMapElement().getObjects(); + assertTrue("Incorrect para element", map.get("e1").getText().equals("Element 1")); + assertTrue("Incorrect para element", map.get("e2").getText().equals("Element 2")); + + map = main.getMap(); + assertTrue("Incorrect para element", map.get("keyE1").getText().equals("Element 1")); + assertTrue("Incorrect para element", map.get("keyE2").getText().equals("Element 2")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + hashMapElement = new HashMapElement(); + map = new HashMap(); + + e1 = new Element(); + e1.setId("e1"); + e1.setText("Element 1"); + hashMapElement.addObject(e1); + map.put("keyE1", e1); + + e2 = new Element(); + e2.setId("e3"); + e2.setText("Element 3"); + hashMapElement.addObject(e2); + map.put("keyE3", e2); + + Element e3 = new Element(); + e3.setId("e4"); + e3.setText("Element 4"); + hashMapElement.addObject(e3); + map.put("keyE4", e3); + + main.setHashMapElement(hashMapElement); + main.setMap(map); + + ocm.update(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + assertNotNull("main.getElements() is null", main.getHashMapElement()); + assertTrue("Incorrect text", main.getText().equals("Main text")); + map = (Map) main.getHashMapElement().getObjects(); + assertTrue("Incorrect para element", map.get("e4").getText().equals("Element 4")); + assertTrue("Incorrect para element", map.get("e4").getText().equals("Element 4")); + + map = main.getMap(); + assertTrue("Incorrect para element", map.get("keyE4").getText().equals("Element 4")); + assertTrue("Incorrect para element", map.get("keyE4").getText().equals("Element 4")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/MultiValueCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationMultiValueCollectionConverterImplTest.java similarity index 54% rename from src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/MultiValueCollectionConverterImplTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationMultiValueCollectionConverterImplTest.java index dfe0d19d..36e50ba2 100644 --- a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/MultiValueCollectionConverterImplTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationMultiValueCollectionConverterImplTest.java @@ -1,81 +1,50 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; +package org.apache.jackrabbit.ocm.manager.collectionconverter; import java.util.ArrayList; -import java.util.Collection; import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.A; -import org.apache.portals.graffito.jcr.testmodel.C; -import org.apache.portals.graffito.jcr.testmodel.MultiValue; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.MultiValue; /** * Test NTCollectionConverterImpl * * @author Christophe Lombart */ -public class MultiValueCollectionConverterImplTest extends TestBase +public class AnnotationMultiValueCollectionConverterImplTest extends AnnotationRepositoryTestBase { - private final static Log log = LogFactory.getLog(MultiValueCollectionConverterImplTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public MultiValueCollectionConverterImplTest(String testName) throws Exception - { - super(testName); - } - public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(MultiValueCollectionConverterImplTest.class); + return new TestSuite(AnnotationMultiValueCollectionConverterImplTest.class); } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - - super.tearDown(); - } + public void testMultiValue() { try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); // -------------------------------------------------------------------------------- // Create and store an object graph in the repository @@ -83,26 +52,26 @@ public void testMultiValue() MultiValue multiValue = new MultiValue(); multiValue.setPath("/test"); - + ArrayList values = new ArrayList(); values.add("Value1"); values.add("Value2"); values.add("Value3"); values.add("Value4"); multiValue.setMultiValues(values); - - persistenceManager.insert(multiValue); - persistenceManager.save(); - + + ocm.insert(multiValue); + ocm.save(); + // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - multiValue = (MultiValue) persistenceManager.getObject(MultiValue.class, "/test"); + // -------------------------------------------------------------------------------- + multiValue = (MultiValue) ocm.getObject( "/test"); assertNotNull("Object is null", multiValue); assertNull("nullMultiValues field is not null", multiValue.getNullMultiValues()); - assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 4); + assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 4); assertTrue("Incorrect collection element", ((String) multiValue.getMultiValues().iterator().next()).equals("Value1")); - + // -------------------------------------------------------------------------------- // Update the object // -------------------------------------------------------------------------------- @@ -113,29 +82,29 @@ public void testMultiValue() values.add("Value4"); values.add("Value5"); multiValue.setMultiValues(values); - - persistenceManager.update(multiValue); - persistenceManager.save(); + + ocm.update(multiValue); + ocm.save(); // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- + // -------------------------------------------------------------------------------- - multiValue = (MultiValue) persistenceManager.getObject(MultiValue.class, "/test"); + multiValue = (MultiValue) ocm.getObject( "/test"); assertNotNull("Object is null", multiValue); assertNull("nullMultiValues field is not null", multiValue.getNullMultiValues()); - assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 5); + assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 5); assertTrue("Incorrect collection element", ((String) multiValue.getMultiValues().iterator().next()).equals("Value1")); - - + + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + } - + } \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationMultiValueWithObjectCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationMultiValueWithObjectCollectionConverterImplTest.java new file mode 100644 index 00000000..29848dec --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationMultiValueWithObjectCollectionConverterImplTest.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.Iterator; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.MultiValueWithObjectCollection; + +/** + * Test NTCollectionConverterImpl + * + * @author : Boni Gopalan + */ +public class AnnotationMultiValueWithObjectCollectionConverterImplTest extends + AnnotationRepositoryTestBase { + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationMultiValueWithObjectCollectionConverterImplTest.class); + } + + public void testMultiValue() { + checkMultiValue(new String[] { "Value1", "Value2", "Value3", "Value4", + "Value5" }, "/test-string", String.class); + checkMultiValue(new Long[] { 1L, 2L, 3L, 4L, 5L }, "/test-long", + Long.class); + } + + public void checkMultiValue(Object[] testData, String nodeName, Class klazz) { + try { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + MultiValueWithObjectCollection multiValue = new MultiValueWithObjectCollection(); + multiValue.setPath(nodeName); + + ArrayList values = new ArrayList(); + values.add(testData[0]); + values.add(testData[1]); + multiValue.setMultiValues(values); + + ocm.insert(multiValue); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + multiValue = (MultiValueWithObjectCollection) ocm + .getObject(nodeName); + assertNotNull("Object is null", multiValue); + assertNull("nullMultiValues field is not null", multiValue + .getNullMultiValues()); + assertTrue("Incorrect number of values", multiValue + .getMultiValues().size() == 2); + Iterator anIterator = multiValue.getMultiValues().iterator(); + assertEquals(testData[0], klazz.cast(anIterator.next())); + assertEquals(testData[1], klazz.cast(anIterator.next())); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + ArrayList values1 = new ArrayList(); + values1.add(testData[2]); + values1.add(testData[3]); + values1.add(testData[4]); + multiValue.setMultiValues(values1); + + ocm.update(multiValue); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + multiValue = (MultiValueWithObjectCollection) ocm + .getObject(nodeName); + assertNotNull("Object is null", multiValue); + assertNull("nullMultiValues field is not null", multiValue + .getNullMultiValues()); + assertTrue("Incorrect number of values", multiValue + .getMultiValues().size() == 3); + assertEquals(testData[2], klazz.cast(multiValue.getMultiValues() + .iterator().next())); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } + +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/NTCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationNTCollectionConverterImplTest.java old mode 100755 new mode 100644 similarity index 55% rename from src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/NTCollectionConverterImplTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationNTCollectionConverterImplTest.java index e5c20c60..e8e5844d --- a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/NTCollectionConverterImplTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationNTCollectionConverterImplTest.java @@ -1,145 +1,147 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; +package org.apache.jackrabbit.ocm.manager.collectionconverter; import java.util.ArrayList; import java.util.Collection; +import java.util.Iterator; import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.A; -import org.apache.portals.graffito.jcr.testmodel.C; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; /** * Test NTCollectionConverterImpl * * @author Christophe Lombart */ -public class NTCollectionConverterImplTest extends TestBase +public class AnnotationNTCollectionConverterImplTest extends AnnotationRepositoryTestBase { - private final static Log log = LogFactory.getLog(NTCollectionConverterImplTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public NTCollectionConverterImplTest(String testName) throws Exception - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(NTCollectionConverterImplTest.class); + return + new TestSuite(AnnotationNTCollectionConverterImplTest.class); } - - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - - super.tearDown(); - } + public void testCollection() { try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); - // -------------------------------------------------------------------------------- - // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with a null collection // -------------------------------------------------------------------------------- Page page = new Page(); page.setPath("/test"); page.setTitle("Page Title"); - + + ocm.insert(page); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + page = (Page) ocm.getObject( "/test"); + assertNull("page.getParagraphs is not null", page.getParagraphs()); + assertTrue("Incorrect page title", page.getTitle().equals("Page Title")); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- ArrayList paragraphs = new ArrayList(); - + paragraphs.add(new Paragraph("Para 1")); paragraphs.add(new Paragraph("Para 2")); paragraphs.add(new Paragraph("Para 3")); page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - persistenceManager.save(); - + + ocm.update(page); + ocm.save(); + // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - page = (Page) persistenceManager.getObject(Page.class, "/test"); + // -------------------------------------------------------------------------------- + page = (Page) ocm.getObject( "/test"); assertNotNull("page.getParagraphs is null", page.getParagraphs()); assertTrue("Incorrect page title", page.getTitle().equals("Page Title")); assertTrue("Incorrect page.getParagraphs size", page.getParagraphs().size() == 3); - assertTrue("Incorrect para element", ((Paragraph) page.getParagraphs().iterator().next()).getText().equals("Para 1")); + assertTrue("Incorrect para element", this.containsText(page.getParagraphs(), "Para 1")); + // -------------------------------------------------------------------------------- // Update the object // -------------------------------------------------------------------------------- paragraphs = new ArrayList(); - + paragraphs.add(new Paragraph("Para 1")); paragraphs.add(new Paragraph("Para 2")); paragraphs.add(new Paragraph("Para 4")); paragraphs.add(new Paragraph("Para 5")); page.setParagraphs(paragraphs); - - persistenceManager.update(page); - persistenceManager.save(); + + ocm.update(page); + ocm.save(); // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- + // -------------------------------------------------------------------------------- - page = (Page) persistenceManager.getObject(Page.class, "/test"); + page = (Page) ocm.getObject( "/test"); assertNotNull("page.getParagraphs is null", page.getParagraphs()); assertTrue("Incorrect page title", page.getTitle().equals("Page Title")); assertTrue("Incorrect page.getParagraphs size", page.getParagraphs().size() == 4); - assertTrue("Incorrect para element", ((Paragraph) page.getParagraphs().iterator().next()).getText().equals("Para 1")); - + assertTrue("Incorrect para element", this.containsText(page.getParagraphs(), "Para 1")); + // -------------------------------------------------------------------------------- // Export to check the content - // -------------------------------------------------------------------------------- + // -------------------------------------------------------------------------------- this.exportDocument("target/NTCollectionExport.xml", "/test", true, false); - + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + + } + + private boolean containsText(Collection paragraphs, String text) + { + Iterator iterator = paragraphs.iterator(); + while (iterator.hasNext()) { + Paragraph paragraph = (Paragraph) iterator.next(); + if (paragraph.getText().equals(text)) + { + return true; + } + + } + return false; + } - } \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationPersonListTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationPersonListTest.java new file mode 100644 index 00000000..d4536e03 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationPersonListTest.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.Person; + +/** + * @author Boni Gopalan + */ +public class AnnotationPersonListTest extends AnnotationRepositoryTestBase +{ + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationPersonListTest.class); + } + + public void testPersonList() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + Person aPerson = buildPerson("PERSON1"); + aPerson.setPath("/person"); + ocm.insert(aPerson); + ocm.save(); + assertNotNull(aPerson.getId()); + String oldParentId = new String(aPerson.getId().toCharArray()); + List childIds = new ArrayList(); + for (Person p : aPerson.getChildren()){ + assertNotNull(p.getId()); + childIds.add(new String(p.getId().toCharArray())); + } + aPerson.setName("UPDATED1"); + ocm.update(aPerson); + Person fb1Person = (Person)ocm.getObject("/person"); + assertNotNull(fb1Person); + assertEquals("UPDATED1", fb1Person.getName()); + assertEquals(oldParentId, fb1Person.getId()); + + //To assert that the ids of the objects in the + //collection has not changed during update. + for (Person p : fb1Person.getChildren()){ + assertTrue(childIds.contains(p.getId())); + } + + Person newChild = new Person(); + newChild.setName("CHILD2"); + + fb1Person.getChildren().add(newChild); + ocm.update(fb1Person); + + Person fb2Person = (Person)ocm.getObject("/person"); + assertNotNull(fb2Person); + assertEquals("UPDATED1", fb2Person.getName()); + assertEquals(oldParentId, fb2Person.getId()); + + //To assert that the ids of the objects in the + //collection has not changed during update. + String child2Id = null; + for (Person p : fb2Person.getChildren()){ + if (!"CHILD2".equals(p.getName())) + assertTrue(childIds.contains(p.getId())); + else{ + assertNotNull(p.getId()); + child2Id = new String(p.getId().toCharArray()); + assertFalse(childIds.contains(p.getId())); + } + } + + //Now remove everyone but CHILD2 and do the update once again + List peopleToRemove = new ArrayList(); + for (Person p : fb2Person.getChildren()){ + if (!"CHILD2".equals(p.getName())) + peopleToRemove.add(p); + } + + for (Person p : peopleToRemove){ + fb2Person.getChildren().remove(p); + } + + ocm.update(fb2Person); + + Person fb3Person = (Person)ocm.getObject("/person"); + assertNotNull(fb3Person); + assertEquals(1, fb3Person.getChildren().size()); + assertEquals(child2Id, fb3Person.getChildren().get(0).getId()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } + + public Person buildPerson(String name){ + Person p = new Person(); + p.setName(name); + Person aChild = new Person(); + aChild.setName("CHILD1"); + List children = new ArrayList(); + children.add(aChild); + p.setChildren(children); + return p; + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationResidualNodesCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationResidualNodesCollectionConverterImplTest.java new file mode 100644 index 00000000..d1f7df0a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationResidualNodesCollectionConverterImplTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.HashMap; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.testmodel.Residual; + +/** + * Test ResidualNodesCollectionConverterImpl + * + * @author Felix Meschberger + * + */ +public class AnnotationResidualNodesCollectionConverterImplTest extends AnnotationRepositoryTestBase +{ + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationResidualNodesCollectionConverterImplTest.class); + } + + + public void testResidualNodes() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with null values + // -------------------------------------------------------------------------------- + + Residual residual = new Residual.ResidualNodes(); + residual.setPath("/test"); + ocm.insert(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertNull("Map is not null", residual.getElements()); + + // -------------------------------------------------------------------------------- + // Update an object graph in the repository + // -------------------------------------------------------------------------------- + residual = new Residual.ResidualNodes(); + residual.setPath("/test"); + + HashMap map = new HashMap(); + map.put("value1", new Paragraph("Value1")); + map.put("value2", new Paragraph("Value2")); + map.put("value3", new Paragraph("Value3")); + map.put("value4", new Paragraph("Value4")); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 4); + assertTrue("Incorrect collection element type", (residual.getElements().get("value2") instanceof Paragraph)); + assertEquals("Incorrect collection element text", ((Paragraph) residual.getElements().get("value2")).getText(), "Value2"); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + map = new HashMap(); + map.put("value11", new Paragraph("Value11")); + map.put("value12", new Paragraph("Value12")); + map.put("value13", new Paragraph("Value13")); + map.put("value14", new Paragraph("Value14")); + map.put("value15", new Paragraph("Value15")); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 5); + assertNull("Unexpected collection element", residual.getElements().get("value2")); + assertTrue("Incorrect collection element type", (residual.getElements().get("value15") instanceof Paragraph)); + assertEquals("Incorrect collection element text", ((Paragraph) residual.getElements().get("value15")).getText(), "Value15"); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationResidualPropertiesCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationResidualPropertiesCollectionConverterImplTest.java new file mode 100644 index 00000000..27b01470 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/AnnotationResidualPropertiesCollectionConverterImplTest.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Residual; + +/** + * Test ResidualPropertiesCollectionConverterImpl + * + * @author Felix Meschberger + * + */ +public class AnnotationResidualPropertiesCollectionConverterImplTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationResidualPropertiesCollectionConverterImplTest.class); + } + + public void testResidualProperties() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with a null hashmap + // -------------------------------------------------------------------------------- + + Residual residual = new Residual.ResidualProperties(); + residual.setPath("/test"); + + ocm.insert(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertNull("Hashmap is not null", residual.getElements()); + + // -------------------------------------------------------------------------------- + // Update an object graph in the repository + // -------------------------------------------------------------------------------- + + residual = new Residual.ResidualProperties(); + residual.setPath("/test"); + + HashMap map = new HashMap(); + map.put("value1", "Value1"); + map.put("value2", "Value2"); + map.put("value3", "Value3"); + map.put("value4", "Value4"); + map.put("value5", Arrays.asList(new String[]{ "Value5-1", "Value5-2" })); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 5); + assertTrue("Incorrect collection element", residual.getElements().get("value2").equals("Value2")); + assertNotNull("Missing collection element", residual.getElements().get("value5")); + assertTrue("Incorrect collection element type", (residual.getElements().get("value5") instanceof List)); + assertEquals("Incorrect collection element list size", ((List) residual.getElements().get("value5")).size(), 2); + assertEquals("Incorrect collection element list value", ((List) residual.getElements().get("value5")).get(0), "Value5-1"); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + map = new HashMap(); + map.put("value11", "Value11"); + map.put("value12", "Value12"); + map.put("value13", "Value13"); + map.put("value14", "Value14"); + map.put("value15", "Value15"); + map.put("value16", Arrays.asList(new String[]{ "Value16-1", "Value16-2" })); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 6); + assertNull("Unexpected collection element", residual.getElements().get("value2")); + assertNull("Unexpected collection element", residual.getElements().get("value5")); + assertTrue("Incorrect collection element", residual.getElements().get("value15").equals("Value15")); + assertNotNull("Missing collection element", residual.getElements().get("value16")); + assertTrue("Incorrect collection element type", (residual.getElements().get("value16") instanceof List)); + assertEquals("Incorrect collection element list size", ((List) residual.getElements().get("value16")).size(), 2); + assertEquals("Incorrect collection element list value", ((List) residual.getElements().get("value16")).get(0), "Value16-1"); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/BeanReferenceMapConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/BeanReferenceMapConverterImplTest.java new file mode 100644 index 00000000..5eb1b404 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/BeanReferenceMapConverterImplTest.java @@ -0,0 +1,437 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import javax.jcr.RepositoryException; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.Main; +import org.apache.jackrabbit.ocm.testmodel.uuid.A; + + +/** + * + * This test validates that the BeanReferenceMapConverterImpl can be used to annotate java.util.Map + * that contain beans stored as references. + * + * + * Map converter used to map reference/uuid property by key into a java.util.Map. + * + * + * @author Vincent Giguère + * + */ +public class BeanReferenceMapConverterImplTest extends AnnotationRepositoryTestBase { + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(BeanReferenceMapConverterImplTest.class); + } + + + public void test_map_of_referenced_nodes_is_persisted_and_reloaded_properly() throws RepositoryException { + ObjectContentManager ocm = getObjectContentManager(); + + ocm.getSession().getRootNode().addNode("test"); + ocm.getSession().getRootNode().addNode("references"); + ocm.getSession().save(); + + A firstA = new A(); + A secondA = new A(); + A thirdA = new A(); + + firstA.setPath("/references/a1"); + secondA.setPath("/references/a2"); + thirdA.setPath("/references/a3"); + + firstA.setStringData("the first"); + secondA.setStringData("the second"); + thirdA.setStringData("the third"); + + ocm.insert(firstA); + ocm.insert(secondA); + ocm.insert(thirdA); + + assertNotNull(firstA.getPath()); + assertNotNull(secondA.getPath()); + assertNotNull(thirdA.getPath()); + + firstA = (A) ocm.getObject(firstA.getPath()); + secondA = (A) ocm.getObject(secondA.getPath()); + thirdA = (A) ocm.getObject(thirdA.getPath()); + + assertNotNull(firstA.getUuid()); + assertNotNull(secondA.getUuid()); + assertNotNull(thirdA.getUuid()); + + + Main main = new Main(); + main.setPath("/test/1"); + main.getReferenceMap().put("keyFirst", firstA); + main.getReferenceMap().put("keySecond", secondA); + main.getReferenceMap().put("keyThird", thirdA); + + + ocm.insert(main); + main = (Main) ocm.getObject(main.getPath()); + + assertEquals("Referenced objects in store were not retrieved.", 3, main.getReferenceMap().size()); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keyFirst")); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keySecond")); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keyThird")); + + + assertEquals("the first", main.getReferenceMap().get("keyFirst").getStringData()); + assertEquals("the second", main.getReferenceMap().get("keySecond").getStringData()); + assertEquals("the third", main.getReferenceMap().get("keyThird").getStringData()); + + } + + public void test_map_can_persist_and_restore_same_node_reference_under_multiple_keys() throws RepositoryException { + ObjectContentManager ocm = getObjectContentManager(); + + ocm.getSession().getRootNode().addNode("test"); + ocm.getSession().getRootNode().addNode("references"); + ocm.getSession().save(); + + A firstA = new A(); + + firstA.setPath("/references/a1"); + + firstA.setStringData("the data"); + + ocm.insert(firstA); + + assertNotNull(firstA.getPath()); + + firstA = (A) ocm.getObject(firstA.getPath()); + + assertNotNull(firstA.getUuid()); + + Main main = new Main(); + main.setPath("/test/1"); + main.getReferenceMap().put("keyFirst", firstA); + main.getReferenceMap().put("keySecond", firstA); + main.getReferenceMap().put("keyThird", firstA); + + + ocm.insert(main); + main = (Main) ocm.getObject(main.getPath()); + + assertEquals("Referenced objects in store were not retrieved.", 3, main.getReferenceMap().size()); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keyFirst")); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keySecond")); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keyThird")); + + + assertEquals("the data", main.getReferenceMap().get("keyFirst").getStringData()); + assertEquals("the data", main.getReferenceMap().get("keySecond").getStringData()); + assertEquals("the data", main.getReferenceMap().get("keyThird").getStringData()); + + + } + + + public void test_map_keys_are_stored_in_relation_to_referenced_node() throws RepositoryException { + + /** + * Make sure that the key to the map is not part of the referenced node. + * In the child node realm, using the @Field(id=true) works, but not with referenced nodes, as they can be referenced by many nodes. + */ + + ObjectContentManager ocm = getObjectContentManager(); + + ocm.getSession().getRootNode().addNode("test"); + ocm.getSession().getRootNode().addNode("references"); + ocm.getSession().save(); + + A firstA = new A(); + A secondA = new A(); + A thirdA = new A(); + + firstA.setPath("/references/a1"); + secondA.setPath("/references/a2"); + thirdA.setPath("/references/a3"); + + firstA.setStringData("the first"); + secondA.setStringData("the second"); + thirdA.setStringData("the third"); + + ocm.insert(firstA); + ocm.insert(secondA); + ocm.insert(thirdA); + + assertNotNull(firstA.getPath()); + assertNotNull(secondA.getPath()); + assertNotNull(thirdA.getPath()); + + firstA = (A) ocm.getObject(firstA.getPath()); + secondA = (A) ocm.getObject(secondA.getPath()); + thirdA = (A) ocm.getObject(thirdA.getPath()); + + assertNotNull(firstA.getUuid()); + assertNotNull(secondA.getUuid()); + assertNotNull(thirdA.getUuid()); + + + Main main = new Main(); + main.setPath("/test/1"); + main.getReferenceMap().put("keyFirst", firstA); + main.getReferenceMap().put("keySecond", secondA); + main.getReferenceMap().put("keyThird", thirdA); + + + Main main2 = new Main(); + main2.setPath("/test/2"); + main2.getReferenceMap().put("AnotherkeyFirst", firstA); + main2.getReferenceMap().put("AnotherkeySecond", secondA); + main2.getReferenceMap().put("AnotherkeyThird", thirdA); + + + ocm.insert(main); + ocm.insert(main2); + main = (Main) ocm.getObject(main.getPath()); + main2 = (Main) ocm.getObject(main2.getPath()); + + assertEquals("Referenced objects in store were not retrieved.", 3, main.getReferenceMap().size()); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keyFirst")); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keySecond")); + assertNotNull("Reference could not be retrieved by its original key", main.getReferenceMap().get("keyThird")); + + + assertEquals("Referenced objects in store were not retrieved.", 3, main2.getReferenceMap().size()); + assertNotNull("Reference could not be retrieved by its original key", main2.getReferenceMap().get("AnotherkeyFirst")); + assertNotNull("Reference could not be retrieved by its original key", main2.getReferenceMap().get("AnotherkeySecond")); + assertNotNull("Reference could not be retrieved by its original key", main2.getReferenceMap().get("AnotherkeyThird")); + + assertEquals("the first", main.getReferenceMap().get("keyFirst").getStringData()); + assertEquals("the second", main.getReferenceMap().get("keySecond").getStringData()); + assertEquals("the third", main.getReferenceMap().get("keyThird").getStringData()); + + assertEquals("the first", main2.getReferenceMap().get("AnotherkeyFirst").getStringData()); + assertEquals("the second", main2.getReferenceMap().get("AnotherkeySecond").getStringData()); + assertEquals("the third", main2.getReferenceMap().get("AnotherkeyThird").getStringData()); + + } + + public void test_converter_removes_deleted_nodes_when_updating() throws RepositoryException { + + ObjectContentManager ocm = getObjectContentManager(); + + ocm.getSession().getRootNode().addNode("test"); + ocm.getSession().getRootNode().addNode("references"); + ocm.getSession().save(); + + A firstA = new A(); + A secondA = new A(); + A thirdA = new A(); + + firstA.setPath("/references/a1"); + secondA.setPath("/references/a2"); + thirdA.setPath("/references/a3"); + + firstA.setStringData("the first"); + secondA.setStringData("the second"); + thirdA.setStringData("the third"); + + ocm.insert(firstA); + ocm.insert(secondA); + ocm.insert(thirdA); + + assertNotNull(firstA.getPath()); + assertNotNull(secondA.getPath()); + assertNotNull(thirdA.getPath()); + + firstA = (A) ocm.getObject(firstA.getPath()); + secondA = (A) ocm.getObject(secondA.getPath()); + thirdA = (A) ocm.getObject(thirdA.getPath()); + + assertNotNull(firstA.getUuid()); + assertNotNull(secondA.getUuid()); + assertNotNull(thirdA.getUuid()); + + + Main main = new Main(); + main.setPath("/test/1"); + main.getReferenceMap().put("keyFirst", firstA); + main.getReferenceMap().put("keySecond", secondA); + main.getReferenceMap().put("keyThird", thirdA); + + + ocm.insert(main); + main = (Main) ocm.getObject(main.getPath()); + + assertEquals("DefaultMapConverterImpl failed to store or reload objects in map property: referencedMap", 3, main.getReferenceMap().size()); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFirst")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keySecond")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyThird")); + + + assertEquals("DefaultMapConverterImpl failed to store objects in map", "the first", main.getReferenceMap().get("keyFirst").getStringData()); + assertEquals("DefaultMapConverterImpl failed to store objects in map", "the second", main.getReferenceMap().get("keySecond").getStringData()); + assertEquals("DefaultMapConverterImpl failed to store objects in map", "the third", main.getReferenceMap().get("keyThird").getStringData()); + + + main.getReferenceMap().remove("keyFirst"); + ocm.update(main); + main = (Main) ocm.getObject(main.getPath()); + assertEquals("DefaultMapConverterImpl failed to store or reload objects in map property: referencedMap", 2, main.getReferenceMap().size()); + assertNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFirst")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keySecond")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyThird")); + + } + + public void test_converter_adds_new_nodes_when_updating() throws RepositoryException { + + ObjectContentManager ocm = getObjectContentManager(); + + ocm.getSession().getRootNode().addNode("test"); + ocm.getSession().getRootNode().addNode("references"); + ocm.getSession().save(); + + A firstA = new A(); + A secondA = new A(); + A thirdA = new A(); + + firstA.setPath("/references/a1"); + secondA.setPath("/references/a2"); + thirdA.setPath("/references/a3"); + + firstA.setStringData("the first"); + secondA.setStringData("the second"); + thirdA.setStringData("the third"); + + ocm.insert(firstA); + ocm.insert(secondA); + ocm.insert(thirdA); + + assertNotNull(firstA.getPath()); + assertNotNull(secondA.getPath()); + assertNotNull(thirdA.getPath()); + + firstA = (A) ocm.getObject(firstA.getPath()); + secondA = (A) ocm.getObject(secondA.getPath()); + thirdA = (A) ocm.getObject(thirdA.getPath()); + + assertNotNull(firstA.getUuid()); + assertNotNull(secondA.getUuid()); + assertNotNull(thirdA.getUuid()); + + + Main main = new Main(); + main.setPath("/test/1"); + main.getReferenceMap().put("keyFirst", firstA); + main.getReferenceMap().put("keySecond", secondA); + + + + ocm.insert(main); + main = (Main) ocm.getObject(main.getPath()); + + assertEquals("DefaultMapConverterImpl failed to store or reload objects in map property: referencedMap", 2, main.getReferenceMap().size()); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFirst")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keySecond")); + assertNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyThird")); + + + main.getReferenceMap().put("keyThird", thirdA); + ocm.update(main); + main = (Main) ocm.getObject(main.getPath()); + assertEquals("DefaultMapConverterImpl failed to store or reload objects in map property: referencedMap", 3, main.getReferenceMap().size()); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFirst")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keySecond")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyThird")); + } + + public void test_converter_can_add_and_remove_nodes_simultaneously_when_updating() throws RepositoryException { + + ObjectContentManager ocm = getObjectContentManager(); + + ocm.getSession().getRootNode().addNode("test"); + ocm.getSession().getRootNode().addNode("references"); + ocm.getSession().save(); + + A firstA = new A(); + A secondA = new A(); + A thirdA = new A(); + A fourthA = new A(); + + firstA.setPath("/references/a1"); + secondA.setPath("/references/a2"); + thirdA.setPath("/references/a3"); + fourthA.setPath("/references/a4"); + + firstA.setStringData("the first"); + secondA.setStringData("the second"); + thirdA.setStringData("the third"); + + ocm.insert(firstA); + ocm.insert(secondA); + ocm.insert(thirdA); + ocm.insert(fourthA); + + assertNotNull(firstA.getPath()); + assertNotNull(secondA.getPath()); + assertNotNull(thirdA.getPath()); + assertNotNull(fourthA.getPath()); + + firstA = (A) ocm.getObject(firstA.getPath()); + secondA = (A) ocm.getObject(secondA.getPath()); + thirdA = (A) ocm.getObject(thirdA.getPath()); + fourthA = (A) ocm.getObject(fourthA.getPath()); + + assertNotNull(firstA.getUuid()); + assertNotNull(secondA.getUuid()); + assertNotNull(thirdA.getUuid()); + assertNotNull(fourthA.getUuid()); + + + Main main = new Main(); + main.setPath("/test/1"); + main.getReferenceMap().put("keyFirst", firstA); + main.getReferenceMap().put("keySecond", secondA); + main.getReferenceMap().put("keyThird", thirdA); + + + + ocm.insert(main); + main = (Main) ocm.getObject(main.getPath()); + + assertEquals("DefaultMapConverterImpl failed to store or reload objects in map property: referencedMap", 3, main.getReferenceMap().size()); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFirst")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keySecond")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyThird")); + assertNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFourth")); + + + main.getReferenceMap().put("keyFourth", fourthA); + main.getReferenceMap().remove("keyFirst"); + ocm.update(main); + main = (Main) ocm.getObject(main.getPath()); + + assertEquals("DefaultMapConverterImpl failed to store or reload objects in map property: referencedMap", 3, main.getReferenceMap().size()); + assertNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFirst")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keySecond")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyThird")); + assertNotNull("DefaultMapConverterImpl failed to store objects in map", main.getReferenceMap().get("keyFourth")); + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterArrayListTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterArrayListTest.java new file mode 100644 index 00000000..69f8560c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterArrayListTest.java @@ -0,0 +1,162 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.ArrayListElement; +import org.apache.jackrabbit.ocm.testmodel.collection.Element; +import org.apache.jackrabbit.ocm.testmodel.collection.Main; + +/** + * @author Christophe Lombart + */ +public class DigesterArrayListTest extends DigesterRepositoryTestBase +{ + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterArrayListTest.class); + } + + public void testArrayList() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // with a null value for the arraylist + // -------------------------------------------------------------------------------- + + Main main = new Main(); + main.setPath("/test"); + main.setText("Main text"); + + ocm.insert(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + ArrayListElement arrayList = main.getArrayListElement(); + List list = main.getList(); + assertNull("main.getArrayListElement is not null", arrayList ); + assertNull("main.getList is not null", list ); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + + ArrayListElement arrayListElement = new ArrayListElement(); + list = new ArrayList(); + + Element e1 = new Element(); + e1.setId("e1"); + e1.setText("Element 1"); + arrayListElement.addObject(e1); + list.add(e1); + + Element e2 = new Element(); + e2.setId("e2"); + e2.setText("Element 2"); + arrayListElement.addObject(e2); + list.add(e2); + + main.setArrayListElement(arrayListElement); + main.setList(list); + ocm.update(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + arrayList = main.getArrayListElement(); + list = main.getList(); + assertNotNull("main.getArrayListElemnt is null", arrayList ); + assertNotNull("main.getList is null", list ); + Collection objects = (Collection) arrayList.getObjects(); + Element[] elements = (Element[]) objects.toArray(new Element[objects.size()]); + assertTrue("Incorrect para element", elements[0].getText().equals("Element 1")); + assertTrue("Incorrect para element", list.get(0).getText().equals("Element 1")); + + + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + arrayListElement = new ArrayListElement(); + list = new ArrayList(); + e1 = new Element(); + e1.setId("e1"); + e1.setText("Element 1"); + arrayListElement.addObject(e1); + list.add(e1); + + e2 = new Element(); + e2.setId("e3"); + e2.setText("Element 3"); + arrayListElement.addObject(e2); + list.add(e2); + + Element e3 = new Element(); + e3.setId("e4"); + e3.setText("Element 4"); + arrayListElement.addObject(e3); + list.add(e3); + + main.setArrayListElement(arrayListElement); + main.setList(list); + + ocm.update(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + arrayList = main.getArrayListElement(); + list = main.getList(); + assertNotNull("main.getArrayListElement() is null", arrayList ); + assertNotNull("main.getList() is null", list ); + objects = (Collection) arrayList.getObjects(); + elements = (Element[]) objects.toArray(new Element[objects.size()]); + assertTrue("Incorrect element", elements[2].getText().equals("Element 4")); + assertTrue("Incorrect element", list.get(2).getText().equals("Element 4")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/DefaultCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterDefaultCollectionConverterImplTest.java similarity index 54% rename from src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/DefaultCollectionConverterImplTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterDefaultCollectionConverterImplTest.java index a44659b6..99f5332a 100755 --- a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/DefaultCollectionConverterImplTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterDefaultCollectionConverterImplTest.java @@ -1,20 +1,20 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; +package org.apache.jackrabbit.ocm.manager.collectionconverter; import java.util.ArrayList; import java.util.Collection; @@ -22,57 +22,113 @@ import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.A; -import org.apache.portals.graffito.jcr.testmodel.C; +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.C; /** * Test DefaultCollectionConverterImpl * * @author Christophe Lombart */ -public class DefaultCollectionConverterImplTest extends TestBase +public class DigesterDefaultCollectionConverterImplTest extends DigesterRepositoryTestBase { - private final static Log log = LogFactory.getLog(DefaultCollectionConverterImplTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public DefaultCollectionConverterImplTest(String testName) throws Exception - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(DefaultCollectionConverterImplTest.class); + return new TestSuite(DigesterDefaultCollectionConverterImplTest.class); } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception + + public void testNull() { - if (getPersistenceManager().objectExists("/test")) + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object with a null collection field + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNull("a.collection is not null", a.getCollection()); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test"); + assertNotNull("a is null", a); + assertNotNull("a.collection is null", a.getCollection()); + assertTrue("Incorrect collection size", a.getCollection().size() == 3); + assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setCollection(null); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNull("a.collection is not null", a.getCollection()); + + // -------------------------------------------------------------------------------- + // Export to check the content + // -------------------------------------------------------------------------------- + this.exportDocument("target/DefaultCollectionConverterExport.xml", "/test", true, false); + + } + catch (Exception e) { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - - super.tearDown(); + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } - + public void testDropElement() { try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); // -------------------------------------------------------------------------------- // Create and store an object graph in the repository @@ -85,70 +141,70 @@ public void testDropElement() C c2 = new C(); c2.setId("second"); c2.setName("Second Element"); - + C c3 = new C(); c3.setId("third"); c3.setName("Third Element"); - - + + Collection collection = new ArrayList(); collection.add(c1); collection.add(c2); collection.add(c3); - + a.setCollection(collection); - - persistenceManager.insert(a); - persistenceManager.save(); - + + ocm.insert(a); + ocm.save(); + // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - a = (A) persistenceManager.getObject(A.class, "/test"); + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); assertNotNull("a.collection is null", a.getCollection()); - assertTrue("Incorrect a.collection size", a.getCollection().size() == 3); + assertEquals("Incorrect a.collection size", 3, a.getCollection().size()); assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); - + // -------------------------------------------------------------------------------- // Update the object // -------------------------------------------------------------------------------- c1 = new C(); c1.setId("new first"); c1.setName("First Element"); - + c2 = new C(); c2.setId("new second"); c2.setName("Second Element"); - + collection = new ArrayList(); collection.add(c1); collection.add(c2); a.setCollection(collection); - - persistenceManager.update(a); - persistenceManager.save(); + + ocm.update(a); + ocm.save(); // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - a = (A) persistenceManager.getObject(A.class, "/test"); + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); assertNotNull("a is null", a); assertNotNull("a.collection is null", a.getCollection()); assertTrue("Incorrect collection size", a.getCollection().size() == 2); assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("new first")); - + // -------------------------------------------------------------------------------- // Export to check the content - // -------------------------------------------------------------------------------- - this.exportDocument("target/DefaultCollectionConverterExport.xml", "/test", true, false); - + // -------------------------------------------------------------------------------- + this.exportDocument("target/DefaultCollectionConverterExport.xml", "/test", true, false); + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + } public void testAddElement() @@ -156,7 +212,7 @@ public void testAddElement() try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); // -------------------------------------------------------------------------------- // Create and store an object graph in the repository @@ -169,74 +225,63 @@ public void testAddElement() C c2 = new C(); c2.setId("second"); c2.setName("Second Element"); - + C c3 = new C(); c3.setId("third"); c3.setName("Third Element"); - - + + Collection collection = new ArrayList(); collection.add(c1); collection.add(c2); collection.add(c3); - + a.setCollection(collection); - - persistenceManager.insert(a); - persistenceManager.save(); - + + ocm.insert(a); + ocm.save(); + // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - a = (A) persistenceManager.getObject(A.class, "/test"); + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); assertNotNull("a.collection is null", a.getCollection()); - assertTrue("Incorrect a.collection size", a.getCollection().size() == 3); - assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); - + assertEquals("Incorrect a.collection size", 3, a.getCollection().size()); + assertEquals("Incorrect a.collection", "first", ((C) a.getCollection().iterator().next()).getId()); + // -------------------------------------------------------------------------------- // Update the object // -------------------------------------------------------------------------------- - c1 = new C(); - c1.setId("first"); - c1.setName("First Element"); - c2 = new C(); - c2.setId("second"); - c2.setName("Second Element"); - - c3 = new C(); - c3.setId("third"); - c3.setName("Third Element"); - C c4 = new C(); c4.setId("Fourth"); c4.setName("Fourth Element"); - + collection = new ArrayList(); collection.add(c1); collection.add(c2); collection.add(c3); collection.add(c4); a.setCollection(collection); - - persistenceManager.update(a); - persistenceManager.save(); + + ocm.update(a); + ocm.save(); // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - a = (A) persistenceManager.getObject(A.class, "/test"); + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); assertNotNull("a is null", a); assertNotNull("a.collection is null", a.getCollection()); - assertTrue("Incorrect collection size", a.getCollection().size() == 4); - assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); - + assertEquals("Incorrect collection size", 4, a.getCollection().size()); + assertEquals("Incorrect a.collection", "first", ((C) a.getCollection().iterator().next()).getId()); + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - - } - + + } + } \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/HashMapTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterHashMapTest.java similarity index 51% rename from src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/HashMapTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterHashMapTest.java index 2f557bd8..debd8cc6 100755 --- a/src/test/org/apache/portals/graffito/jcr/persistence/collectionconverter/impl/HashMapTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterHashMapTest.java @@ -1,110 +1,104 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.collectionconverter.impl; +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.Map; import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.hashmap.Element; -import org.apache.portals.graffito.jcr.testmodel.hashmap.HashMapElement; -import org.apache.portals.graffito.jcr.testmodel.hashmap.Main; +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.Element; +import org.apache.jackrabbit.ocm.testmodel.collection.HashMapElement; +import org.apache.jackrabbit.ocm.testmodel.collection.Main; /** * Test NTCollectionConverterImpl * * @author Christophe Lombart */ -public class HashMapTest extends TestBase +public class DigesterHashMapTest extends DigesterRepositoryTestBase { - private final static Log log = LogFactory.getLog(HashMapTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public HashMapTest(String testName) throws Exception - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(HashMapTest.class); + return new TestSuite(DigesterHashMapTest.class); } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - - super.tearDown(); - } - + public void testHashMap() { try { - PersistenceManager persistenceManager = getPersistenceManager(); - + ObjectContentManager ocm = getObjectContentManager(); // -------------------------------------------------------------------------------- - // Create and store an object graph in the repository + // Create and store an object graph in the repository with null hashmap // -------------------------------------------------------------------------------- Main main = new Main(); main.setPath("/test"); main.setText("Main text"); - + + ocm.insert(main); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertTrue("Incorrect text", main.getText().equals("Main text")); + assertNull("HashMap is not null", main.getHashMapElement()); + + // -------------------------------------------------------------------------------- + // Update an object graph in the repository + // -------------------------------------------------------------------------------- + + main = new Main(); + main.setPath("/test"); + main.setText("Main text"); + HashMapElement hashMapElement = new HashMapElement(); Element e1 = new Element(); e1.setId("e1"); e1.setText("Element 1"); hashMapElement.addObject(e1); - + Element e2 = new Element(); e2.setId("e2"); e2.setText("Element 2"); hashMapElement.addObject(e2); - - main.setElements(hashMapElement); - - persistenceManager.insert(main); - persistenceManager.save(); - + + main.setHashMapElement(hashMapElement); + + ocm.update(main); + ocm.save(); + // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - main = (Main) persistenceManager.getObject(Main.class, "/test"); - assertNotNull("main.getElements() is null", main.getElements()); - assertTrue("Incorrect text", main.getText().equals("Main text")); - assertTrue("Incorrect para element", ((Element) main.getElements().get("e1")).getText().equals("Element 1")); - + // -------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("main.getHashMap() is null", main.getHashMapElement()); + assertTrue("Incorrect text", main.getText().equals("Main text")); + Map map = (Map) main.getHashMapElement().getObjects(); + assertTrue("Incorrect para element", ((Element) map.get("e1")).getText().equals("Element 1")); + // -------------------------------------------------------------------------------- // Update the object // -------------------------------------------------------------------------------- @@ -113,7 +107,7 @@ public void testHashMap() e1.setId("e1"); e1.setText("Element 1"); hashMapElement.addObject(e1); - + e2 = new Element(); e2.setId("e3"); e2.setText("Element 3"); @@ -123,27 +117,28 @@ public void testHashMap() e3.setId("e4"); e3.setText("Element 4"); hashMapElement.addObject(e3); - main.setElements(hashMapElement); - - persistenceManager.update(main); - persistenceManager.save(); + main.setHashMapElement(hashMapElement); + + ocm.update(main); + ocm.save(); // -------------------------------------------------------------------------------- // Get the object - // -------------------------------------------------------------------------------- - assertNotNull("main.getElements() is null", main.getElements()); - assertTrue("Incorrect text", main.getText().equals("Main text")); - assertTrue("Incorrect para element", ((Element) main.getElements().get("e4")).getText().equals("Element 4")); - + // -------------------------------------------------------------------------------- + assertNotNull("main.getElements() is null", main.getHashMapElement()); + assertTrue("Incorrect text", main.getText().equals("Main text")); + map = (Map) main.getHashMapElement().getObjects(); + assertTrue("Incorrect para element", ((Element) map.get("e4")).getText().equals("Element 4")); + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + } - + } \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterMultiValueCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterMultiValueCollectionConverterImplTest.java new file mode 100644 index 00000000..253258f2 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterMultiValueCollectionConverterImplTest.java @@ -0,0 +1,110 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.MultiValue; + +/** + * Test NTCollectionConverterImpl + * + * @author Christophe Lombart + */ +public class DigesterMultiValueCollectionConverterImplTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterMultiValueCollectionConverterImplTest.class); + } + + + public void testMultiValue() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + MultiValue multiValue = new MultiValue(); + multiValue.setPath("/test"); + + ArrayList values = new ArrayList(); + values.add("Value1"); + values.add("Value2"); + values.add("Value3"); + values.add("Value4"); + multiValue.setMultiValues(values); + + ocm.insert(multiValue); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + multiValue = (MultiValue) ocm.getObject( "/test"); + assertNotNull("Object is null", multiValue); + assertNull("nullMultiValues field is not null", multiValue.getNullMultiValues()); + assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 4); + assertTrue("Incorrect collection element", ((String) multiValue.getMultiValues().iterator().next()).equals("Value1")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + values = new ArrayList(); + values.add("Value1"); + values.add("Value2"); + values.add("Value3"); + values.add("Value4"); + values.add("Value5"); + multiValue.setMultiValues(values); + + ocm.update(multiValue); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + multiValue = (MultiValue) ocm.getObject( "/test"); + assertNotNull("Object is null", multiValue); + assertNull("nullMultiValues field is not null", multiValue.getNullMultiValues()); + assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 5); + assertTrue("Incorrect collection element", ((String) multiValue.getMultiValues().iterator().next()).equals("Value1")); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterMultiValueWithObjectCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterMultiValueWithObjectCollectionConverterImplTest.java new file mode 100644 index 00000000..f01e194f --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterMultiValueWithObjectCollectionConverterImplTest.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.Iterator; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.MultiValueWithObjectCollection; + +/** + * Test NTCollectionConverterImpl + * + * @author : Boni Gopalan + */ +public class DigesterMultiValueWithObjectCollectionConverterImplTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterMultiValueWithObjectCollectionConverterImplTest.class); + } + + public void testMultiValue(){ + checkMultiValue(new String [] {"Value1", "Value2", "Value3", "Value4", "Value5"}, "/test-string", String.class); + checkMultiValue(new Long [] {1L, 2L, 3L, 4L, 5L}, "/test-long", Long.class); + } + + public void checkMultiValue(Object [] testData, String nodeName, Class klazz ) + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + + MultiValueWithObjectCollection multiValue = new MultiValueWithObjectCollection(); + multiValue.setPath(nodeName); + + ArrayList values = new ArrayList(); + values.add(testData[0]); + values.add(testData[1]); + multiValue.setMultiValues(values); + + ocm.insert(multiValue); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + multiValue = (MultiValueWithObjectCollection) ocm.getObject( nodeName); + assertNotNull("Object is null", multiValue); + assertNull("nullMultiValues field is not null", multiValue.getNullMultiValues()); + assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 2); + Iterator anIterator = multiValue.getMultiValues().iterator(); + assertEquals(testData[0], klazz.cast(anIterator.next())); + assertEquals(testData[1], klazz.cast(anIterator.next())); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + ArrayList values1 = new ArrayList(); + values1.add(testData[2]); + values1.add(testData[3]); + values1.add(testData[4]); + multiValue.setMultiValues(values1); + + ocm.update(multiValue); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + multiValue = (MultiValueWithObjectCollection) ocm.getObject(nodeName); + assertNotNull("Object is null", multiValue); + assertNull("nullMultiValues field is not null", multiValue.getNullMultiValues()); + assertTrue("Incorrect number of values", multiValue.getMultiValues().size() == 3); + assertEquals(testData[2], klazz.cast(multiValue.getMultiValues().iterator().next())); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterNTCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterNTCollectionConverterImplTest.java new file mode 100755 index 00000000..e25531d7 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterNTCollectionConverterImplTest.java @@ -0,0 +1,146 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + +/** + * Test NTCollectionConverterImpl + * + * @author Christophe Lombart + */ +public class DigesterNTCollectionConverterImplTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return + new TestSuite(DigesterNTCollectionConverterImplTest.class); + } + + + public void testCollection() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with a null collection + // -------------------------------------------------------------------------------- + + Page page = new Page(); + page.setPath("/test"); + page.setTitle("Page Title"); + + ocm.insert(page); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + page = (Page) ocm.getObject( "/test"); + assertNull("page.getParagraphs is not null", page.getParagraphs()); + assertTrue("Incorrect page title", page.getTitle().equals("Page Title")); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + page.setParagraphs(paragraphs); + + ocm.update(page); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + page = (Page) ocm.getObject( "/test"); + assertNotNull("page.getParagraphs is null", page.getParagraphs()); + assertTrue("Incorrect page title", page.getTitle().equals("Page Title")); + assertTrue("Incorrect page.getParagraphs size", page.getParagraphs().size() == 3); + assertTrue("Incorrect para element", this.containsText(page.getParagraphs(),"Para 1")); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 4")); + paragraphs.add(new Paragraph("Para 5")); + page.setParagraphs(paragraphs); + + ocm.update(page); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + page = (Page) ocm.getObject( "/test"); + assertNotNull("page.getParagraphs is null", page.getParagraphs()); + assertTrue("Incorrect page title", page.getTitle().equals("Page Title")); + assertTrue("Incorrect page.getParagraphs size", page.getParagraphs().size() == 4); + assertTrue("Incorrect para element", this.containsText(page.getParagraphs(),"Para 1")); + + // -------------------------------------------------------------------------------- + // Export to check the content + // -------------------------------------------------------------------------------- + this.exportDocument("target/NTCollectionExport.xml", "/test", true, false); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + private boolean containsText(Collection paragraphs, String text) + { + Iterator iterator = paragraphs.iterator(); + while (iterator.hasNext()) { + Paragraph paragraph = (Paragraph) iterator.next(); + if (paragraph.getText().equals(text)) + { + return true; + } + + } + return false; + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterPersonListTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterPersonListTest.java new file mode 100644 index 00000000..9ba1a7f7 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterPersonListTest.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.collection.Person; + +/** + * @author Boni Gopalan + */ +public class DigesterPersonListTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterPersonListTest.class); + } + + public void testPersonList() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + Person aPerson = buildPerson("PERSON1"); + aPerson.setPath("/person"); + ocm.insert(aPerson); + ocm.save(); + assertNotNull(aPerson.getId()); + String oldParentId = new String(aPerson.getId().toCharArray()); + List childIds = new ArrayList(); + for (Person p : aPerson.getChildren()){ + assertNotNull(p.getId()); + childIds.add(new String(p.getId().toCharArray())); + } + aPerson.setName("UPDATED1"); + ocm.update(aPerson); + Person fb1Person = (Person)ocm.getObject("/person"); + assertNotNull(fb1Person); + assertEquals("UPDATED1", fb1Person.getName()); + assertEquals(oldParentId, fb1Person.getId()); + + //To assert that the ids of the objects in the + //collection has not changed during update. + for (Person p : fb1Person.getChildren()){ + assertTrue(childIds.contains(p.getId())); + } + + Person newChild = new Person(); + newChild.setName("CHILD2"); + + fb1Person.getChildren().add(newChild); + ocm.update(fb1Person); + + Person fb2Person = (Person)ocm.getObject("/person"); + assertNotNull(fb2Person); + assertEquals("UPDATED1", fb2Person.getName()); + assertEquals(oldParentId, fb2Person.getId()); + + //To assert that the ids of the objects in the + //collection has not changed during update. + String child2Id = null; + for (Person p : fb2Person.getChildren()){ + if (!"CHILD2".equals(p.getName())) + assertTrue(childIds.contains(p.getId())); + else{ + assertNotNull(p.getId()); + child2Id = new String(p.getId().toCharArray()); + assertFalse(childIds.contains(p.getId())); + } + } + + //Now remove everyone but CHILD2 and do the update once again + List peopleToRemove = new ArrayList(); + for (Person p : fb2Person.getChildren()){ + if (!"CHILD2".equals(p.getName())) + peopleToRemove.add(p); + } + + for (Person p : peopleToRemove){ + fb2Person.getChildren().remove(p); + } + + ocm.update(fb2Person); + + Person fb3Person = (Person)ocm.getObject("/person"); + assertNotNull(fb3Person); + assertEquals(1, fb3Person.getChildren().size()); + assertEquals(child2Id, fb3Person.getChildren().get(0).getId()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } + + public Person buildPerson(String name){ + Person p = new Person(); + p.setName(name); + Person aChild = new Person(); + aChild.setName("CHILD1"); + List children = new ArrayList(); + children.add(aChild); + p.setChildren(children); + return p; + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterResidualNodesCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterResidualNodesCollectionConverterImplTest.java new file mode 100644 index 00000000..88643cbf --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterResidualNodesCollectionConverterImplTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.HashMap; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.testmodel.Residual; + +/** + * Test ResidualNodesCollectionConverterImpl + * + * @author Felix Meschberger + * + */ +public class DigesterResidualNodesCollectionConverterImplTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterResidualNodesCollectionConverterImplTest.class); + } + + public void testResidualNodes() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with null values + // -------------------------------------------------------------------------------- + + Residual residual = new Residual.ResidualNodes(); + residual.setPath("/test"); + ocm.insert(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertNull("Map is not null", residual.getElements()); + + // -------------------------------------------------------------------------------- + // Update an object graph in the repository + // -------------------------------------------------------------------------------- + residual = new Residual.ResidualNodes(); + residual.setPath("/test"); + + HashMap map = new HashMap(); + map.put("value1", new Paragraph("Value1")); + map.put("value2", new Paragraph("Value2")); + map.put("value3", new Paragraph("Value3")); + map.put("value4", new Paragraph("Value4")); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 4); + assertTrue("Incorrect collection element type", (residual.getElements().get("value2") instanceof Paragraph)); + assertEquals("Incorrect collection element text", ((Paragraph) residual.getElements().get("value2")).getText(), "Value2"); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + map = new HashMap(); + map.put("value11", new Paragraph("Value11")); + map.put("value12", new Paragraph("Value12")); + map.put("value13", new Paragraph("Value13")); + map.put("value14", new Paragraph("Value14")); + map.put("value15", new Paragraph("Value15")); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 5); + assertNull("Unexpected collection element", residual.getElements().get("value2")); + assertTrue("Incorrect collection element type", (residual.getElements().get("value15") instanceof Paragraph)); + assertEquals("Incorrect collection element text", ((Paragraph) residual.getElements().get("value15")).getText(), "Value15"); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterResidualPropertiesCollectionConverterImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterResidualPropertiesCollectionConverterImplTest.java new file mode 100644 index 00000000..d9d33958 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/DigesterResidualPropertiesCollectionConverterImplTest.java @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Residual; + +/** + * Test ResidualPropertiesCollectionConverterImpl + * + * @author Felix Meschberger + * + */ +public class DigesterResidualPropertiesCollectionConverterImplTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterResidualPropertiesCollectionConverterImplTest.class); + } + + + public void testResidualProperties() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository with a null hashmap + // -------------------------------------------------------------------------------- + + Residual residual = new Residual.ResidualProperties(); + residual.setPath("/test"); + + ocm.insert(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertNull("Hashmap is not null", residual.getElements()); + + // -------------------------------------------------------------------------------- + // Update an object graph in the repository + // -------------------------------------------------------------------------------- + + residual = new Residual.ResidualProperties(); + residual.setPath("/test"); + + HashMap map = new HashMap(); + map.put("value1", "Value1"); + map.put("value2", "Value2"); + map.put("value3", "Value3"); + map.put("value4", "Value4"); + map.put("value5", Arrays.asList(new String[]{ "Value5-1", "Value5-2" })); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 5); + assertTrue("Incorrect collection element", residual.getElements().get("value2").equals("Value2")); + assertNotNull("Missing collection element", residual.getElements().get("value5")); + assertTrue("Incorrect collection element type", (residual.getElements().get("value5") instanceof List)); + assertEquals("Incorrect collection element list size", ((List) residual.getElements().get("value5")).size(), 2); + assertEquals("Incorrect collection element list value", ((List) residual.getElements().get("value5")).get(0), "Value5-1"); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + map = new HashMap(); + map.put("value11", "Value11"); + map.put("value12", "Value12"); + map.put("value13", "Value13"); + map.put("value14", "Value14"); + map.put("value15", "Value15"); + map.put("value16", Arrays.asList(new String[]{ "Value16-1", "Value16-2" })); + residual.setElements(map); + + ocm.update(residual); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + + residual = (Residual) ocm.getObject( "/test"); + assertNotNull("Object is null", residual); + assertTrue("Incorrect number of values", residual.getElements().size() == 6); + assertNull("Unexpected collection element", residual.getElements().get("value2")); + assertNull("Unexpected collection element", residual.getElements().get("value5")); + assertTrue("Incorrect collection element", residual.getElements().get("value15").equals("Value15")); + assertNotNull("Missing collection element", residual.getElements().get("value16")); + assertTrue("Incorrect collection element type", (residual.getElements().get("value16") instanceof List)); + assertEquals("Incorrect collection element list size", ((List) residual.getElements().get("value16")).size(), 2); + assertEquals("Incorrect collection element list value", ((List) residual.getElements().get("value16")).get(0), "Value16-1"); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/MapReferenceValueEncoderTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/MapReferenceValueEncoderTest.java new file mode 100644 index 00000000..54236682 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/collectionconverter/MapReferenceValueEncoderTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.manager.collectionconverter; + +import junit.framework.TestCase; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.MapReferenceValueEncoder; + +/** + * TODO: JAVADOC + *

+ * Created by Vincent Giguere + * Date: Jun 9, 2008 + * Time: 3:08:28 PM + */ +public class MapReferenceValueEncoderTest extends TestCase{ + + + public void testEncode_key_and_reference() + { + String key = "value1"; + String reference = "aReference"; + assertTrue(MapReferenceValueEncoder.encodeKeyAndReference(key, reference).contains(key)); + assertTrue(MapReferenceValueEncoder.encodeKeyAndReference(key, reference).contains(reference)); + + } + + + public void testDecode_key() + { + String key = "value1"; + String reference = "aReference"; + assertEquals(key , MapReferenceValueEncoder.decodeKey(MapReferenceValueEncoder.encodeKeyAndReference(key, reference))); + } + + + public void testDecode_reference() + { + String key = "value1"; + String reference = "aReference"; + assertEquals(reference , MapReferenceValueEncoder.decodeReference(MapReferenceValueEncoder.encodeKeyAndReference(key, reference))); + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/AnnotationSimpleEnumerationTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/AnnotationSimpleEnumerationTest.java new file mode 100644 index 00000000..8aa31376 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/AnnotationSimpleEnumerationTest.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.enumeration; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; + +/** + * Test Simple Enumeration mappings + * + * @author Boni Gopalan + */ +public class AnnotationSimpleEnumerationTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationSimpleEnumerationTest.class); + } + + public void testMapSimpleEnumeration() + { + try { + new SimpleEnumerationTestBase(getObjectContentManager()).testMapSimpleEnumeration(); + } catch (Throwable e) { + e.printStackTrace(); + fail("Tests resulted in exception"); + } + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/DigesterSimpleEnumerationTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/DigesterSimpleEnumerationTest.java new file mode 100644 index 00000000..4b130697 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/DigesterSimpleEnumerationTest.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.enumeration; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; + +/** + * Test Persisting and retrieving Enum values. + * + * @author Boni Gopalan + */ +public class DigesterSimpleEnumerationTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return + new TestSuite(DigesterSimpleEnumerationTest.class); + } + + public void testMapSimpleEnumeration() + { + try { + new SimpleEnumerationTestBase(getObjectContentManager()).testMapSimpleEnumeration(); + } catch (Throwable e) { + e.printStackTrace(); + fail("Tests resulted in exception"); + } + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/SimpleEnumerationTestBase.java b/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/SimpleEnumerationTestBase.java new file mode 100644 index 00000000..e0829b5e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/enumeration/SimpleEnumerationTestBase.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.enumeration; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.enumeration.Odyssey; +import org.apache.jackrabbit.ocm.testmodel.enumeration.Planet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; + +/** + * Test Simple Enumeration mappings + * + * @author Boni Gopalan + */ +public class SimpleEnumerationTestBase +{ + private final static Logger log = LoggerFactory.getLogger(SimpleEnumerationTestBase.class); + ObjectContentManager ocm; + public SimpleEnumerationTestBase(ObjectContentManager ocm){ + this.ocm = ocm; + } + + public void testMapSimpleEnumeration() + { + try + { + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + Odyssey odyssey = new Odyssey(); + odyssey.setPath("/odesseyToMars"); + odyssey.setGoingTo(Planet.MARS); + odyssey.setStartingFrom(Planet.EARTH); + odyssey.setStops(getStops()); + ocm.insert(odyssey); + Odyssey fbOdessey = (Odyssey)ocm.getObject("/odesseyToMars"); + assertTrue("Fetched back Enum did not match the saved data", fbOdessey.getGoingTo() == Planet.MARS); + assertTrue("Fetched back Enum did not match the saved data", fbOdessey.getStartingFrom() == Planet.EARTH); + assertTrue("Fetched back Enum did not match the saved Enum Collection Size", fbOdessey.getStops().size() == odyssey.getStops().size()); + List stops = getStops(); + List fbStops = fbOdessey.getStops(); + for (Planet aStop : stops){ + assertContains("Fetched back list did not contain :" + aStop.toString(), aStop, fbStops); + log.info("Contains Enum : " + aStop.toString()); + } + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + private static void assertContains(String message, Planet value, List aList){ + for (Enum anObject : aList){ + if (anObject == null){ + if (value == null) return; + continue; + } + if (anObject.equals(value)) return; + } + fail(message); + } + + private List getStops(){ + List stops = new ArrayList(); + stops.add(Planet.MARS); + stops.add(Planet.MERCURY); + stops.add(Planet.JUPITER); + return stops; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AllTests.java new file mode 100644 index 00000000..8ead20a7 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AllTests.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.inheritance; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.inheritance"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationInheritanceConcreteClassTest.class); + suite.addTestSuite(AnnotationInheritanceHierarchyTest.class); + suite.addTestSuite(DigesterInheritanceConcreteClassTest.class); + suite.addTestSuite(DigesterInheritanceHierarchyTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AnnotationInheritanceConcreteClassTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AnnotationInheritanceConcreteClassTest.java new file mode 100644 index 00000000..3749c260 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AnnotationInheritanceConcreteClassTest.java @@ -0,0 +1,428 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.inheritance; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.CmsObjectImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.ContentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentExtImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.FolderImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationInheritanceConcreteClassTest extends AnnotationRepositoryTestBase { + private final static Logger log = LoggerFactory.getLogger(AnnotationInheritanceConcreteClassTest.class); + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationInheritanceConcreteClassTest.class); + } + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a Document + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + + ocm.insert(document); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + document = (DocumentImpl) ocm.getObject( "/document1"); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + + //--------------------------------------------------------------------------------------------------------- + // Update a descendant object + //--------------------------------------------------------------------------------------------------------- + document.setName("anotherName"); + ocm.update(document); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the updated descendant object + //--------------------------------------------------------------------------------------------------------- + document = (DocumentImpl) ocm.getObject( "/document1"); + assertEquals("document name is incorrect", document.getName(), "anotherName"); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream", document.getDocumentStream().getEncoding().equals("utf-8")); + + CmsObjectImpl cmsObject = (CmsObjectImpl) ocm.getObject( "/document1"); + assertEquals("cmsObject name is incorrect", cmsObject.getName(), "anotherName"); + assertEquals("cmsObject path is invalid", cmsObject.getPath(), "/document1"); + + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name 1"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document2"); + document.setName("document name 2"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document3"); + document.setName("document 3"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 3".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + FolderImpl folder = new FolderImpl(); + folder.setPath("/folder1"); + folder.setName("folder1"); + ocm.insert(folder); + + + document = new DocumentImpl(); + document.setName("document4"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 4".getBytes()); + document.setDocumentStream(documentStream); + + FolderImpl subFolder = new FolderImpl(); + subFolder.setName("subfolder"); + + folder = new FolderImpl(); + folder.setPath("/folder2"); + folder.setName("folder2"); + folder.addChild(document); + folder.addChild(subFolder); + ocm.insert(folder); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folders found on the root level + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(FolderImpl.class); + Query query = queryManager.createQuery(filter); + filter.setScope("/"); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of folders found", result.size(), 2); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2", FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Documents + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(DocumentImpl.class); + + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + FolderImpl folder2 = (FolderImpl) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + + CmsObjectImpl cmsObject = (CmsObjectImpl) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", cmsObject); + assertTrue("Invalid instance for folder 2", cmsObject instanceof FolderImpl); + assertEquals("Invalid number of documents found in folder2 children", folder2.getChildren().size(),2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Contents (ancestor of Documents) + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(ContentImpl.class); + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found on the root level + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObjectImpl.class); + filter.setScope("/"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),5); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found anywhere + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObjectImpl.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),7); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/subfolder",FolderImpl.class)); + + } + + public void testBeanCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + FolderImpl folder = new FolderImpl(); + folder.setPath("/mainfolder"); + folder.setName("Main folder"); + + for (int i=1; i<=100;i++) + { + DocumentImpl document = new DocumentImpl(); + document.setName("document" + i); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + folder.addChild(document); + + FolderImpl subFolder = new FolderImpl(); + subFolder.setName("folder" + i); + subFolder.addChild(document); + folder.addChild(subFolder); + + } + log.debug("Save the folder and its 200 children"); + ocm.insert(folder); + ocm.save(); + log.debug("End - Save the folder and its 200 children"); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folder + //--------------------------------------------------------------------------------------------------------- + folder = (FolderImpl) ocm.getObject("/mainfolder"); + assertNotNull("Folder is null",folder); + Collection children = folder.getChildren(); + assertEquals("Invalid number of children", children.size(), 200); + for (int i=1; i<=100;i++) + { + assertTrue("Invalid item in the collection : " +"/mainfolder/document" + i , this.contains(children, "/mainfolder/document" + i,DocumentImpl.class)); + assertTrue("Invalid item in the collection : " + "/mainfolder/folder" + i, this.contains(children, "/mainfolder/folder" + i, FolderImpl.class)); + } + + + } + + + public void testRetrieveExtension() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a Document + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + + ocm.insert(document); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + CmsObject cmsObject = (CmsObject) ocm.getObject( CmsObject.class, "/document1" ); + assertNotNull("Document not loaded", cmsObject); + assertTrue("Document of wrong type " + cmsObject.getClass().getName(), cmsObject instanceof DocumentImpl); + + document = (DocumentImpl) cmsObject; + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + try { + Class clazz = Folder.class; + cmsObject = (CmsObject) ocm.getObject( clazz, "/document1" ); + fail("Unexpected Mapping for DocumentImpl node to " + clazz); + } catch (JcrMappingException jme) { + // this is expected as class should not be acceptable + } + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveExtensionMissingExtends() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a Document + //--------------------------------------------------------------------------------------------------------- + DocumentExtImpl document = new DocumentExtImpl(); + document.setPath("/document1"); + document.setExtInfo("ext info"); + document.setName("document name"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + + ocm.insert(document); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + CmsObject cmsObject = (CmsObject) ocm.getObject( CmsObject.class, "/document1" ); + assertNotNull("Document not loaded", cmsObject); + assertTrue("Document of wrong type " + cmsObject.getClass().getName(), cmsObject instanceof DocumentExtImpl); + + document = (DocumentExtImpl) cmsObject; + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Ext Info is invalid", document.getExtInfo(), "ext info"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AnnotationInheritanceHierarchyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AnnotationInheritanceHierarchyTest.java new file mode 100644 index 00000000..f15887ec --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/AnnotationInheritanceHierarchyTest.java @@ -0,0 +1,226 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.inheritance; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; + +/** + * Test inheritance with node type per hierarchy stategy (with discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationInheritanceHierarchyTest extends AnnotationRepositoryTestBase { + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationInheritanceHierarchyTest.class); + } + + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a descendant object + //--------------------------------------------------------------------------------------------------------- + Descendant descendant = new Descendant(); + descendant.setDescendantField("descendantValue"); + descendant.setAncestorField("ancestorValue"); + descendant.setIntField(200); + descendant.setPath("/test"); + ocm.insert(descendant); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a descendant object + //--------------------------------------------------------------------------------------------------------- + descendant = null; + descendant = (Descendant) ocm.getObject( "/test"); + assertEquals("Descendant path is invalid", descendant.getPath(), "/test"); + assertEquals("Descendant ancestorField is invalid", descendant.getAncestorField(), "ancestorValue"); + assertEquals("Descendant descendantField is invalid", descendant.getDescendantField(), "descendantValue"); + assertEquals("Descendant intField is invalid", descendant.getIntField(), 200); + + //--------------------------------------------------------------------------------------------------------- + // Update a descendant object + //--------------------------------------------------------------------------------------------------------- + descendant.setAncestorField("anotherAncestorValue"); + descendant.setIntField(123); + ocm.update(descendant); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the updated descendant object + //--------------------------------------------------------------------------------------------------------- + descendant = null; + descendant = (Descendant) ocm.getObject( "/test"); + assertEquals("Descendant path is invalid", descendant.getPath(), "/test"); + assertEquals("Descendant ancestorField is invalid", descendant.getAncestorField(), "anotherAncestorValue"); + assertEquals("Descendant descendantField is invalid", descendant .getDescendantField(), "descendantValue"); + assertEquals("Descendant intField is invalid", descendant.getIntField(), 123); + + Ancestor ancestor = (Ancestor) ocm.getObject("/test"); + assertTrue("Invalid object instance", ancestor instanceof Descendant ); + assertEquals("Ancestor path is invalid", ancestor.getPath(), "/test"); + assertEquals("Ancestor ancestorField is invalid", ancestor.getAncestorField(), "anotherAncestorValue"); + + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + ObjectContentManager ocm = getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert descendant objects + //--------------------------------------------------------------------------------------------------------- + Descendant descendant = new Descendant(); + descendant.setDescendantField("descendantValue"); + descendant.setAncestorField("ancestorValue"); + descendant.setPath("/descendant1"); + ocm.insert(descendant); + + descendant = new Descendant(); + descendant.setDescendantField("descendantValue2"); + descendant.setAncestorField("ancestorValue2"); + descendant.setPath("/descendant2"); + ocm.insert(descendant); + + SubDescendant subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue2"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant"); + subDescendant.setSubDescendantField("subdescendantvalue"); + ocm.insert(subDescendant); + + subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue3"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant2"); + subDescendant.setSubDescendantField("subdescendantvalue1"); + ocm.insert(subDescendant); + + + AnotherDescendant anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue3"); + anotherDescendant.setPath("/anotherdescendant1"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue4"); + anotherDescendant.setPath("/anotherdescendant2"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue2"); + anotherDescendant.setAncestorField("ancestorValue5"); + anotherDescendant.setPath("/anotherdescendant3"); + ocm.insert(anotherDescendant); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Descendant class + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Descendant.class); + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of Descendant found", result.size(), 4); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant1", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant", SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant2", SubDescendant.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve AnotherDescendant class + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(AnotherDescendant.class); + filter.addEqualTo("anotherDescendantField", "anotherDescendantValue"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of AnotherDescendant found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant1", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant2", AnotherDescendant.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve some descendants & subdescendants + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Descendant.class); + filter.addEqualTo("descendantField","descendantValue2"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant", SubDescendant.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all class + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Ancestor.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),7); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant1", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant", SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant2", SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant1", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant2", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant3", AnotherDescendant.class)); + + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/DigesterInheritanceConcreteClassTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/DigesterInheritanceConcreteClassTest.java new file mode 100644 index 00000000..66dd6b5d --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/DigesterInheritanceConcreteClassTest.java @@ -0,0 +1,429 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.inheritance; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.CmsObjectImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.ContentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentExtImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.FolderImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterInheritanceConcreteClassTest extends DigesterRepositoryTestBase { + private final static Logger log = LoggerFactory.getLogger(DigesterInheritanceConcreteClassTest.class); + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterInheritanceConcreteClassTest.class); + } + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a Document + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + + ocm.insert(document); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + document = (DocumentImpl) ocm.getObject( "/document1"); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + + //--------------------------------------------------------------------------------------------------------- + // Update a descendant object + //--------------------------------------------------------------------------------------------------------- + document.setName("anotherName"); + ocm.update(document); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the updated descendant object + //--------------------------------------------------------------------------------------------------------- + document = (DocumentImpl) ocm.getObject( "/document1"); + assertEquals("document name is incorrect", document.getName(), "anotherName"); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream", document.getDocumentStream().getEncoding().equals("utf-8")); + + CmsObjectImpl cmsObject = (CmsObjectImpl) ocm.getObject( "/document1"); + assertEquals("cmsObject name is incorrect", cmsObject.getName(), "anotherName"); + assertEquals("cmsObject path is invalid", cmsObject.getPath(), "/document1"); + + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name 1"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document2"); + document.setName("document name 2"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document3"); + document.setName("document 3"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 3".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + FolderImpl folder = new FolderImpl(); + folder.setPath("/folder1"); + folder.setName("folder1"); + ocm.insert(folder); + + + document = new DocumentImpl(); + document.setName("document4"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 4".getBytes()); + document.setDocumentStream(documentStream); + + FolderImpl subFolder = new FolderImpl(); + subFolder.setName("subfolder"); + + folder = new FolderImpl(); + folder.setPath("/folder2"); + folder.setName("folder2"); + folder.addChild(document); + folder.addChild(subFolder); + ocm.insert(folder); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folders found on the root level + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(FolderImpl.class); + Query query = queryManager.createQuery(filter); + filter.setScope("/"); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of folders found", result.size(), 2); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2", FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Documents + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(DocumentImpl.class); + + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + FolderImpl folder2 = (FolderImpl) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + + CmsObjectImpl cmsObject = (CmsObjectImpl) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", cmsObject); + assertTrue("Invalid instance for folder 2", cmsObject instanceof FolderImpl); + assertEquals("Invalid number of documents found in folder2 children", folder2.getChildren().size(),2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Contents (ancestor of Documents) + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(ContentImpl.class); + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found on the root level + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObjectImpl.class); + filter.setScope("/"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),5); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found anywhere + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObjectImpl.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),7); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/subfolder",FolderImpl.class)); + + } + + public void testBeanCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + FolderImpl folder = new FolderImpl(); + folder.setPath("/mainfolder"); + folder.setName("Main folder"); + + for (int i=1; i<=100;i++) + { + DocumentImpl document = new DocumentImpl(); + document.setName("document" + i); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + folder.addChild(document); + + FolderImpl subFolder = new FolderImpl(); + subFolder.setName("folder" + i); + subFolder.addChild(document); + folder.addChild(subFolder); + + } + log.debug("Save the folder and its 200 children"); + ocm.insert(folder); + ocm.save(); + log.debug("End - Save the folder and its 200 children"); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folder + //--------------------------------------------------------------------------------------------------------- + folder = (FolderImpl) ocm.getObject("/mainfolder"); + assertNotNull("Folder is null",folder); + Collection children = folder.getChildren(); + assertEquals("Invalid number of children", children.size(), 200); + for (int i=1; i<=100;i++) + { + assertTrue("Invalid item in the collection : " +"/mainfolder/document" + i , this.contains(children, "/mainfolder/document" + i,DocumentImpl.class)); + assertTrue("Invalid item in the collection : " + "/mainfolder/folder" + i, this.contains(children, "/mainfolder/folder" + i, FolderImpl.class)); + } + + + } + + + public void testRetrieveExtension() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a Document + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + + ocm.insert(document); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + CmsObject cmsObject = (CmsObject) ocm.getObject( CmsObject.class, "/document1" ); + assertNotNull("Document not loaded", cmsObject); + assertTrue("Document of wrong type " + cmsObject.getClass().getName(), cmsObject instanceof DocumentImpl); + + document = (DocumentImpl) cmsObject; + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + try { + Class clazz = Folder.class; + cmsObject = (CmsObject) ocm.getObject( clazz, "/document1" ); + fail("Unexpected Mapping for DocumentImpl node to " + clazz); + } catch (JcrMappingException jme) { + // this is expected as class should not be acceptable + } + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveExtensionMissingExtends() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a Document + //--------------------------------------------------------------------------------------------------------- + DocumentExtImpl document = new DocumentExtImpl(); + document.setPath("/document1"); + document.setExtInfo("ext info"); + document.setName("document name"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + + ocm.insert(document); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + + CmsObject cmsObject = (CmsObject) ocm.getObject( CmsObject.class, "/document1" ); + assertNotNull("Document not loaded", cmsObject); + assertTrue("Document of wrong type " + cmsObject.getClass().getName(), cmsObject instanceof DocumentExtImpl); + + document = (DocumentExtImpl) cmsObject; + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Ext Info is invalid", document.getExtInfo(), "ext info"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/DigesterInheritanceHierarchyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/DigesterInheritanceHierarchyTest.java new file mode 100644 index 00000000..61da959d --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/inheritance/DigesterInheritanceHierarchyTest.java @@ -0,0 +1,225 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.inheritance; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; + +/** + * Test inheritance with node type per hierarchy stategy (with discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterInheritanceHierarchyTest extends DigesterRepositoryTestBase { + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterInheritanceHierarchyTest.class); + } + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a descendant object + //--------------------------------------------------------------------------------------------------------- + Descendant descendant = new Descendant(); + descendant.setDescendantField("descendantValue"); + descendant.setAncestorField("ancestorValue"); + descendant.setIntField(200); + descendant.setPath("/test"); + ocm.insert(descendant); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a descendant object + //--------------------------------------------------------------------------------------------------------- + descendant = null; + descendant = (Descendant) ocm.getObject( "/test"); + assertEquals("Descendant path is invalid", descendant.getPath(), "/test"); + assertEquals("Descendant ancestorField is invalid", descendant.getAncestorField(), "ancestorValue"); + assertEquals("Descendant descendantField is invalid", descendant.getDescendantField(), "descendantValue"); + assertEquals("Descendant intField is invalid", descendant.getIntField(), 200); + + //--------------------------------------------------------------------------------------------------------- + // Update a descendant object + //--------------------------------------------------------------------------------------------------------- + descendant.setAncestorField("anotherAncestorValue"); + descendant.setIntField(123); + ocm.update(descendant); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the updated descendant object + //--------------------------------------------------------------------------------------------------------- + descendant = null; + descendant = (Descendant) ocm.getObject( "/test"); + assertEquals("Descendant path is invalid", descendant.getPath(), "/test"); + assertEquals("Descendant ancestorField is invalid", descendant.getAncestorField(), "anotherAncestorValue"); + assertEquals("Descendant descendantField is invalid", descendant .getDescendantField(), "descendantValue"); + assertEquals("Descendant intField is invalid", descendant.getIntField(), 123); + + Ancestor ancestor = (Ancestor) ocm.getObject("/test"); + assertTrue("Invalid object instance", ancestor instanceof Descendant ); + assertEquals("Ancestor path is invalid", ancestor.getPath(), "/test"); + assertEquals("Ancestor ancestorField is invalid", ancestor.getAncestorField(), "anotherAncestorValue"); + + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert descendant objects + //--------------------------------------------------------------------------------------------------------- + Descendant descendant = new Descendant(); + descendant.setDescendantField("descendantValue"); + descendant.setAncestorField("ancestorValue"); + descendant.setPath("/descendant1"); + ocm.insert(descendant); + + descendant = new Descendant(); + descendant.setDescendantField("descendantValue2"); + descendant.setAncestorField("ancestorValue2"); + descendant.setPath("/descendant2"); + ocm.insert(descendant); + + SubDescendant subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue2"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant"); + subDescendant.setSubDescendantField("subdescendantvalue"); + ocm.insert(subDescendant); + + subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue3"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant2"); + subDescendant.setSubDescendantField("subdescendantvalue1"); + ocm.insert(subDescendant); + + + AnotherDescendant anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue3"); + anotherDescendant.setPath("/anotherdescendant1"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue4"); + anotherDescendant.setPath("/anotherdescendant2"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue2"); + anotherDescendant.setAncestorField("ancestorValue5"); + anotherDescendant.setPath("/anotherdescendant3"); + ocm.insert(anotherDescendant); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Descendant class + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Descendant.class); + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of Descendant found", result.size(), 4); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant1", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant", SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant2", SubDescendant.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve AnotherDescendant class + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(AnotherDescendant.class); + filter.addEqualTo("anotherDescendantField", "anotherDescendantValue"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of AnotherDescendant found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant1", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant2", AnotherDescendant.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve some descendants & subdescendants + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Descendant.class); + filter.addEqualTo("descendantField","descendantValue2"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant", SubDescendant.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all class + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Ancestor.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),7); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant1", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant", SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant2", SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant1", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant2", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant3", AnotherDescendant.class)); + + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AllTests.java new file mode 100644 index 00000000..dab9ef0f --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AllTests.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.interfaces; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.interfaces"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationConcreteClassTest.class); + suite.addTestSuite(DigesterConcreteClassTest.class); + suite.addTestSuite(AnnotationInterfaceHierarchyTest.class); + suite.addTestSuite(DigesterInterfaceHierarchyTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AnnotationConcreteClassTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AnnotationConcreteClassTest.java new file mode 100644 index 00000000..6984ca67 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AnnotationConcreteClassTest.java @@ -0,0 +1,339 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.interfaces; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.FolderImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Content; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Document; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test interface (with discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationConcreteClassTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationConcreteClassTest.class); + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationConcreteClassTest.class); + } + + + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert + //--------------------------------------------------------------------------------------------------------- + DocumentImpl documentImpl = new DocumentImpl(); + documentImpl.setPath("/document1"); + documentImpl.setName("document name"); + documentImpl.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + documentImpl.setDocumentStream(documentStream); + Document document = documentImpl; + + ocm.insert(document); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve + //--------------------------------------------------------------------------------------------------------- + document = (Document) ocm.getObject( "/document1"); + assertTrue("Invalid implementation for Document", document instanceof DocumentImpl); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + //--------------------------------------------------------------------------------------------------------- + // Update a document + //--------------------------------------------------------------------------------------------------------- + document.setName("anotherName"); + ocm.update(document); + ocm.save(); + + // --------------------------------------------------------------------------------------------------------- + // Retrieve the updated descendant object + //--------------------------------------------------------------------------------------------------------- + document = (Document) ocm.getObject( "/document1"); + assertTrue("Invalid implementation for Document", document instanceof DocumentImpl); + assertEquals("document name is incorrect", document.getName(), "anotherName"); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream", document.getDocumentStream().getEncoding().equals("utf-8")); + + CmsObject cmsObject = (CmsObject) ocm.getObject( "/document1"); + assertEquals("cmsObject name is incorrect", cmsObject.getName(), "anotherName"); + assertEquals("cmsObject path is invalid", cmsObject.getPath(), "/document1"); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name 1"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document2"); + document.setName("document name 2"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document3"); + document.setName("document 3"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 3".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + FolderImpl folder = new FolderImpl(); + folder.setPath("/folder1"); + folder.setName("folder1"); + ocm.insert(folder); + + + document = new DocumentImpl(); + document.setName("document4"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 4".getBytes()); + document.setDocumentStream(documentStream); + + FolderImpl subFolder = new FolderImpl(); + subFolder.setName("subfolder"); + + folder = new FolderImpl(); + folder.setPath("/folder2"); + folder.setName("folder2"); + folder.addChild(document); + folder.addChild(subFolder); + ocm.insert(folder); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folders found on the root level + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Folder.class); + Query query = queryManager.createQuery(filter); + filter.setScope("/"); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of folders found", result.size(), 2); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2", FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Documents + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Document.class); + + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + Folder folder2 = (Folder) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + + CmsObject cmsObject = (CmsObject) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", cmsObject); + assertTrue("Invalid instance for folder 2", cmsObject instanceof FolderImpl); + assertEquals("Invalid number of documents found in folder2 children", folder2.getChildren().size(),2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + Folder childFolder = (Folder) ocm.getObject( "/folder2/subfolder"); + Folder parenFolder = childFolder.getParentFolder(); + assertNotNull("parent folder is null", parenFolder); + assertTrue("Invalid instance for parent folder", parenFolder instanceof FolderImpl); + assertEquals("Invalid number of documents found in folder2 children", parenFolder.getChildren().size(),2); + assertTrue("Invalid item in the collection", this.contains(parenFolder.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(parenFolder.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Contents (ancestor of Documents) + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Content.class); + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found on the root level + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObject.class); + filter.setScope("/"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),5); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found anywhere + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObject.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),7); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/subfolder",FolderImpl.class)); + +} + + +public void testBeanCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + Folder folder = new FolderImpl(); + folder.setPath("/mainfolder"); + folder.setName("Main folder"); + + for (int i=1; i<=100;i++) + { + Document document = new DocumentImpl(); + document.setName("document" + i); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + folder.addChild(document); + + Folder subFolder = new FolderImpl(); + subFolder.setName("folder" + i); + subFolder.addChild(document); + folder.addChild(subFolder); + + } + log.debug("Save the folder and its 200 children"); + ocm.insert(folder); + ocm.save(); + log.debug("End - Save the folder and its 200 children"); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folder + //--------------------------------------------------------------------------------------------------------- + folder = (Folder) ocm.getObject("/mainfolder"); + assertNotNull("Folder is null",folder); + Collection children = folder.getChildren(); + assertEquals("Invalid number of children", children.size(), 200); + for (int i=1; i<=100;i++) + { + + assertTrue("Invalid item in the collection : " +"/mainfolder/document" + i , this.contains(children, "/mainfolder/document" + i,DocumentImpl.class)); + assertTrue("Invalid item in the collection : " + "/mainfolder/folder" + i, this.contains(children, "/mainfolder/folder" + i, FolderImpl.class)); + } +} + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AnnotationInterfaceHierarchyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AnnotationInterfaceHierarchyTest.java new file mode 100644 index 00000000..d108f28f --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/AnnotationInterfaceHierarchyTest.java @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.interfaces; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; +import org.apache.jackrabbit.ocm.testmodel.interfaces.AnotherInterface; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; + +/** + * Test interface (with discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationInterfaceHierarchyTest extends AnnotationRepositoryTestBase { + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationInterfaceHierarchyTest.class); + } + + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert + //--------------------------------------------------------------------------------------------------------- + AnotherDescendant anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue"); + anotherDescendant.setPath("/test"); + ocm.insert(anotherDescendant); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve + //--------------------------------------------------------------------------------------------------------- + Interface result = (Interface) ocm.getObject("/test"); + assertNotNull("Object is null", result); + anotherDescendant = (AnotherDescendant) result; + + assertEquals("Descendant path is invalid", anotherDescendant.getPath(), "/test"); + assertEquals("Descendant ancestorField is invalid", anotherDescendant.getAncestorField(), "ancestorValue"); + assertEquals("Descendant descendantField is invalid", anotherDescendant .getAnotherDescendantField(), "anotherDescendantValue"); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert descendant objects + //--------------------------------------------------------------------------------------------------------- + Descendant descendant = new Descendant(); + descendant.setDescendantField("descendantValue"); + descendant.setAncestorField("ancestorValue"); + descendant.setPath("/descendant1"); + ocm.insert(descendant); + + descendant = new Descendant(); + descendant.setDescendantField("descendantValue2"); + descendant.setAncestorField("ancestorValue2"); + descendant.setPath("/descendant2"); + ocm.insert(descendant); + + SubDescendant subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue2"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant"); + subDescendant.setSubDescendantField("subdescendantvalue"); + ocm.insert(subDescendant); + + subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue3"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant2"); + subDescendant.setSubDescendantField("subdescendantvalue1"); + ocm.insert(subDescendant); + + + AnotherDescendant anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue3"); + anotherDescendant.setPath("/anotherdescendant1"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue4"); + anotherDescendant.setPath("/anotherdescendant2"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue2"); + anotherDescendant.setAncestorField("ancestorValue5"); + anotherDescendant.setPath("/anotherdescendant3"); + ocm.insert(anotherDescendant); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Descendant class (implements Interface.class) + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Interface.class); + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of interface found", result.size(),3); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant1", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant2", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant3", AnotherDescendant.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Descendant class and its children (implements AnotherInterface.class) + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(AnotherInterface.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of interface found", result.size(),4); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant1", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant",SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant2",SubDescendant.class)); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/DigesterConcreteClassTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/DigesterConcreteClassTest.java new file mode 100644 index 00000000..48920324 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/DigesterConcreteClassTest.java @@ -0,0 +1,335 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.interfaces; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.FolderImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Content; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Document; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test interface (with discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterConcreteClassTest extends DigesterRepositoryTestBase { + private final static Logger log = LoggerFactory.getLogger(DigesterConcreteClassTest.class); + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterConcreteClassTest.class); + } + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert + //--------------------------------------------------------------------------------------------------------- + DocumentImpl documentImpl = new DocumentImpl(); + documentImpl.setPath("/document1"); + documentImpl.setName("document name"); + documentImpl.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + documentImpl.setDocumentStream(documentStream); + Document document = documentImpl; + + ocm.insert(document); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve + //--------------------------------------------------------------------------------------------------------- + document = (Document) ocm.getObject( "/document1"); + assertTrue("Invalid implementation for Document", document instanceof DocumentImpl); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream ", document.getDocumentStream().getEncoding().equals("utf-8")); + + //--------------------------------------------------------------------------------------------------------- + // Update a document + //--------------------------------------------------------------------------------------------------------- + document.setName("anotherName"); + ocm.update(document); + ocm.save(); + + // --------------------------------------------------------------------------------------------------------- + // Retrieve the updated descendant object + //--------------------------------------------------------------------------------------------------------- + document = (Document) ocm.getObject( "/document1"); + assertTrue("Invalid implementation for Document", document instanceof DocumentImpl); + assertEquals("document name is incorrect", document.getName(), "anotherName"); + assertEquals("Document path is invalid", document.getPath(), "/document1"); + assertEquals("Content type is invalid", document.getContentType(), "plain/text"); + assertNotNull("document stream is null", document.getDocumentStream()); + assertTrue("Invalid document stream", document.getDocumentStream().getEncoding().equals("utf-8")); + + CmsObject cmsObject = (CmsObject) ocm.getObject( "/document1"); + assertEquals("cmsObject name is incorrect", cmsObject.getName(), "anotherName"); + assertEquals("cmsObject path is invalid", cmsObject.getPath(), "/document1"); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + DocumentImpl document = new DocumentImpl(); + document.setPath("/document1"); + document.setName("document name 1"); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document2"); + document.setName("document name 2"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + document = new DocumentImpl(); + document.setPath("/document3"); + document.setName("document 3"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 3".getBytes()); + document.setDocumentStream(documentStream); + ocm.insert(document); + + FolderImpl folder = new FolderImpl(); + folder.setPath("/folder1"); + folder.setName("folder1"); + ocm.insert(folder); + + + document = new DocumentImpl(); + document.setName("document4"); + document.setContentType("plain/text"); + documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content 4".getBytes()); + document.setDocumentStream(documentStream); + + FolderImpl subFolder = new FolderImpl(); + subFolder.setName("subfolder"); + + folder = new FolderImpl(); + folder.setPath("/folder2"); + folder.setName("folder2"); + folder.addChild(document); + folder.addChild(subFolder); + ocm.insert(folder); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folders found on the root level + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Folder.class); + Query query = queryManager.createQuery(filter); + filter.setScope("/"); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of folders found", result.size(), 2); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2", FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Documents + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Document.class); + + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve folder2 + //--------------------------------------------------------------------------------------------------------- + Folder folder2 = (Folder) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", folder2); + assertEquals("Invalid number of cms object found in folder2 children", folder2.getChildren().size() ,2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + + CmsObject cmsObject = (CmsObject) ocm.getObject( "/folder2"); + assertNotNull("folder 2 is null", cmsObject); + assertTrue("Invalid instance for folder 2", cmsObject instanceof FolderImpl); + assertEquals("Invalid number of documents found in folder2 children", folder2.getChildren().size(),2); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(folder2.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + Folder childFolder = (Folder) ocm.getObject( "/folder2/subfolder"); + Folder parenFolder = childFolder.getParentFolder(); + assertNotNull("parent folder is null", parenFolder); + assertTrue("Invalid instance for parent folder", parenFolder instanceof FolderImpl); + assertEquals("Invalid number of documents found in folder2 children", parenFolder.getChildren().size(),2); + assertTrue("Invalid item in the collection", this.contains(parenFolder.getChildren(), "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(parenFolder.getChildren(), "/folder2/subfolder", FolderImpl.class)); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Contents (ancestor of Documents) + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(Content.class); + filter.addLike("name", "document name%"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of documents found", result.size(),2); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found on the root level + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObject.class); + filter.setScope("/"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),5); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve all cmsobjects found anywhere + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(CmsObject.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid ancestor object found", result.size(),7); + assertTrue("Invalid item in the collection", this.contains(result, "/document1", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document2", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/document3", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/document4", DocumentImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder1",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2",FolderImpl.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/folder2/subfolder",FolderImpl.class)); + +} + + +public void testBeanCollection() { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert cmsobjects + //--------------------------------------------------------------------------------------------------------- + Folder folder = new FolderImpl(); + folder.setPath("/mainfolder"); + folder.setName("Main folder"); + + for (int i=1; i<=100;i++) + { + Document document = new DocumentImpl(); + document.setName("document" + i); + document.setContentType("plain/text"); + DocumentStream documentStream = new DocumentStream(); + documentStream.setEncoding("utf-8"); + documentStream.setContent("Test Content".getBytes()); + document.setDocumentStream(documentStream); + folder.addChild(document); + + Folder subFolder = new FolderImpl(); + subFolder.setName("folder" + i); + subFolder.addChild(document); + folder.addChild(subFolder); + + } + log.debug("Save the folder and its 200 children"); + ocm.insert(folder); + ocm.save(); + log.debug("End - Save the folder and its 200 children"); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Folder + //--------------------------------------------------------------------------------------------------------- + folder = (Folder) ocm.getObject("/mainfolder"); + assertNotNull("Folder is null",folder); + Collection children = folder.getChildren(); + assertEquals("Invalid number of children", children.size(), 200); + for (int i=1; i<=100;i++) + { + + assertTrue("Invalid item in the collection : " +"/mainfolder/document" + i , this.contains(children, "/mainfolder/document" + i,DocumentImpl.class)); + assertTrue("Invalid item in the collection : " + "/mainfolder/folder" + i, this.contains(children, "/mainfolder/folder" + i, FolderImpl.class)); + } +} + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/DigesterInterfaceHierarchyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/DigesterInterfaceHierarchyTest.java new file mode 100644 index 00000000..2c14d183 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/DigesterInterfaceHierarchyTest.java @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.interfaces; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; +import org.apache.jackrabbit.ocm.testmodel.interfaces.AnotherInterface; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; + +/** + * Test interface (with discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterInterfaceHierarchyTest extends DigesterRepositoryTestBase { + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterInterfaceHierarchyTest.class); + } + + + public void testRetrieveSingleton() { + + try { + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert + //--------------------------------------------------------------------------------------------------------- + AnotherDescendant anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue"); + anotherDescendant.setPath("/test"); + ocm.insert(anotherDescendant); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve + //--------------------------------------------------------------------------------------------------------- + Interface result = (Interface) ocm.getObject("/test"); + assertNotNull("Object is null", result); + anotherDescendant = (AnotherDescendant) result; + + assertEquals("Descendant path is invalid", anotherDescendant.getPath(), "/test"); + assertEquals("Descendant ancestorField is invalid", anotherDescendant.getAncestorField(), "ancestorValue"); + assertEquals("Descendant descendantField is invalid", anotherDescendant .getAnotherDescendantField(), "anotherDescendantValue"); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + public void testRetrieveCollection() { + + ObjectContentManager ocm = this.getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert descendant objects + //--------------------------------------------------------------------------------------------------------- + Descendant descendant = new Descendant(); + descendant.setDescendantField("descendantValue"); + descendant.setAncestorField("ancestorValue"); + descendant.setPath("/descendant1"); + ocm.insert(descendant); + + descendant = new Descendant(); + descendant.setDescendantField("descendantValue2"); + descendant.setAncestorField("ancestorValue2"); + descendant.setPath("/descendant2"); + ocm.insert(descendant); + + SubDescendant subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue2"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant"); + subDescendant.setSubDescendantField("subdescendantvalue"); + ocm.insert(subDescendant); + + subDescendant = new SubDescendant(); + subDescendant.setDescendantField("descendantValue3"); + subDescendant.setAncestorField("ancestorValue2"); + subDescendant.setPath("/subdescendant2"); + subDescendant.setSubDescendantField("subdescendantvalue1"); + ocm.insert(subDescendant); + + + AnotherDescendant anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue3"); + anotherDescendant.setPath("/anotherdescendant1"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue"); + anotherDescendant.setAncestorField("ancestorValue4"); + anotherDescendant.setPath("/anotherdescendant2"); + ocm.insert(anotherDescendant); + + anotherDescendant = new AnotherDescendant(); + anotherDescendant.setAnotherDescendantField("anotherDescendantValue2"); + anotherDescendant.setAncestorField("ancestorValue5"); + anotherDescendant.setPath("/anotherdescendant3"); + ocm.insert(anotherDescendant); + + + Atomic a = new Atomic(); + a.setPath("/atomic"); + a.setBooleanPrimitive(true); + ocm.insert(a); + + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Descendant class (implements Interface.class) + //--------------------------------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Interface.class); + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of interface found", result.size(),3); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant1", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant2", AnotherDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/anotherdescendant3", AnotherDescendant.class)); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve Descendant class and its children (implements AnotherInterface.class) + //--------------------------------------------------------------------------------------------------------- + queryManager = ocm.getQueryManager(); + filter = queryManager.createFilter(AnotherInterface.class); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertEquals("Invalid number of interface found", result.size(),4); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant1", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/descendant2", Descendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant",SubDescendant.class)); + assertTrue("Invalid item in the collection", this.contains(result, "/subdescendant2",SubDescendant.class)); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/ListOfInterfaceTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/ListOfInterfaceTest.java new file mode 100644 index 00000000..db2ac859 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/interfaces/ListOfInterfaceTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.interfaces; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.interfaces.EntityA; +import org.apache.jackrabbit.ocm.testmodel.interfaces.EntityB; +import org.apache.jackrabbit.ocm.testmodel.interfaces.MyInterface; + + +public class ListOfInterfaceTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(ListOfInterfaceTest.class); + } + + + + public void testListOfInterface() { + + try { + ObjectContentManager ocm = getObjectContentManager(); + + EntityA a = new EntityA(); + a.setPath("/test"); + + List bList = new ArrayList(); + EntityB b = new EntityB(); + b.setId("ID_B"); + b.setName("NAME_B"); + bList.add(b); + + a.setEntityB(bList); + + ocm.insert(a); + ocm.save(); + + + a = (EntityA) ocm.getObject("/test"); + bList = a.getEntityB(); + assertNotNull(bList); + assertEquals(1, bList.size()); + + + ocm.remove("/test"); + ocm.save(); + + + + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + } + + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AllTests.java new file mode 100644 index 00000000..84c7591d --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AllTests.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.jcrnodetype; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.jcrnodetype"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationJcrNodeTypeTest.class); + suite.addTestSuite(DigesterJcrNodeTypeTest.class); + suite.addTestSuite(AnnotationJcrPropertyTest.class); + suite.addTestSuite(DigesterJcrPropertyTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AnnotationJcrNodeTypeTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AnnotationJcrNodeTypeTest.java new file mode 100644 index 00000000..23fa5b91 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AnnotationJcrNodeTypeTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.jcrnodetype; + +import java.io.ByteArrayInputStream; +import java.util.Calendar; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.File; +import org.apache.jackrabbit.ocm.testmodel.Folder; +import org.apache.jackrabbit.ocm.testmodel.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationJcrNodeTypeTest extends AnnotationRepositoryTestBase { + private final static Logger log = LoggerFactory.getLogger(AnnotationJcrNodeTypeTest.class); + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationJcrNodeTypeTest.class); + } + + public void testRetrieveSingleton() + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a folder (class mapped to jcr:folder) with one file (class mapped to jcr:file) + //--------------------------------------------------------------------------------------------------------- + Resource resource = new Resource(); + resource.setData(new ByteArrayInputStream("this is the content".getBytes())); + resource.setLastModified(Calendar.getInstance()); + resource.setMimeType("plain/text"); + File file = new File(); + file.setResource(resource); + + + Folder folder = new Folder(); + folder.setPath("/folder1"); + folder.addChild(file); + + ocm.insert(folder); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + folder = (Folder) ocm.getObject( "/folder1"); + assertNotNull("folder is null", folder); + log.info("Folder creation date : " + folder.getCreationDate()); + assertTrue("Invalid number of children", folder.getChildren().size() == 1); + file = (File) folder.getChildren().iterator().next(); + assertNotNull("resource is null", file.getResource()); + log.info("File resource calendar: " + file.getResource().getLastModified()); // The prop is autocreated + + + } + catch (Exception e) + { + log.error("testRetrieveSingleton failed", e); + fail(); + } + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AnnotationJcrPropertyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AnnotationJcrPropertyTest.java new file mode 100644 index 00000000..9436e225 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/AnnotationJcrPropertyTest.java @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.jcrnodetype; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.OcmTestProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationJcrPropertyTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationJcrPropertyTest.class); + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationJcrPropertyTest.class); + } + + public void testRequiredProperty() + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + //--------------------------------------------------------------------------------------------------------- + // Insert without the mandatory field + //--------------------------------------------------------------------------------------------------------- + + OcmTestProperty ocmTestProperty = new OcmTestProperty(); + ocmTestProperty.setPath("/test"); + ocmTestProperty.setRequiredProp("requiredPropValue"); + ocmTestProperty.setRequiredWithConstraintsProp("abc"); + + try + { + ocm.insert(ocmTestProperty); + fail("Incorrect insert operation - the mandatory fields have no value"); + } + catch(Exception e) + { + // Normal behaviour + ocm.refresh(false); + } + + //--------------------------------------------------------------------------------------------------------- + // Insert with the mandatory fields + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty.setMandatoryProp("mandatoryValue"); + ocmTestProperty.setMandatoryWithConstaintsProp("xx"); + ocm.insert(ocmTestProperty); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + assertTrue("Invalid required property", ocmTestProperty.getRequiredProp().equals("requiredPropValue")); + assertTrue("Invalid required property with constraints", ocmTestProperty.getRequiredWithConstraintsProp().equals("abc")); + assertTrue("Invalid autocreated property", ocmTestProperty.getAutoCreatedProp().equals("aaa")); + assertTrue("Invalid autocreated property", ocmTestProperty.getAutoCreatedWithConstraintsProp().equals("ccc")); + assertTrue("Invalid protected property", ocmTestProperty.getProtectedWithDefaultValueProp().equals("protectedValue")); + + //--------------------------------------------------------------------------------------------------------- + // update the property requiredWithConstraintsProp with bad value + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + ocmTestProperty.setRequiredWithConstraintsProp("invalid value"); + try + { + ocm.update(ocmTestProperty); + ocm.save(); + fail("Invalid value was accepted for requiredWithConstraintsProp"); + } + catch(Exception e) + { + // Do nothing - normal behaviour, the value + } + + //--------------------------------------------------------------------------------------------------------- + // update the property AutoCreatedWithConstraintsProp with bad value + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + ocmTestProperty.setAutoCreatedWithConstraintsProp("invalid value"); + try + { + ocm.update(ocmTestProperty); + ocm.save(); + fail("Invalid value was accepted for autoCreatedWithConstraintsProp "); + } + catch(Exception e) + { + // Do nothing - normal behaviour, the value is not valid + + } + + //--------------------------------------------------------------------------------------------------------- + // update the property mandatoryWithConstaintsProp with bad value + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + ocmTestProperty.setMandatoryWithConstaintsProp("yy"); + try + { + ocm.update(ocmTestProperty); + ocm.save(); + fail("Invalid value was accepted for mandatoryWithConstaintsProp"); + } + catch(Exception e) + { + // expected + } + + + } + catch (Exception e) + { + log.error("testRequiredProperty failed", e); + fail(); + } + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/DigesterJcrNodeTypeTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/DigesterJcrNodeTypeTest.java new file mode 100644 index 00000000..ad312a6a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/DigesterJcrNodeTypeTest.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.jcrnodetype; + +import java.io.ByteArrayInputStream; +import java.util.Calendar; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.File; +import org.apache.jackrabbit.ocm.testmodel.Folder; +import org.apache.jackrabbit.ocm.testmodel.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterJcrNodeTypeTest extends DigesterRepositoryTestBase { + private final static Logger log = LoggerFactory.getLogger(DigesterJcrNodeTypeTest.class); + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterJcrNodeTypeTest.class); + } + + + public void testRetrieveSingleton() + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + + //--------------------------------------------------------------------------------------------------------- + // Insert a folder (class mapped to jcr:folder) with one file (class mapped to jcr:file) + //--------------------------------------------------------------------------------------------------------- + Resource resource = new Resource(); + resource.setData(new ByteArrayInputStream("this is the content".getBytes())); + resource.setLastModified(Calendar.getInstance()); + resource.setMimeType("plain/text"); + File file = new File(); + file.setResource(resource); + + + Folder folder = new Folder(); + folder.setPath("/folder1"); + folder.addChild(file); + + ocm.insert(folder); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve a document object + //--------------------------------------------------------------------------------------------------------- + folder = (Folder) ocm.getObject( "/folder1"); + assertNotNull("folder is null", folder); + log.info("Folder creation date : " + folder.getCreationDate()); + assertTrue("Invalid number of children", folder.getChildren().size() == 1); + file = (File) folder.getChildren().iterator().next(); + assertNotNull("resource is null", file.getResource()); + log.info("File resource calendar: " + file.getResource().getLastModified()); // The prop is autocreated + + + } + catch (Exception e) + { + log.error("testRetrieveSingleton failed", e); + fail(); + } + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/DigesterJcrPropertyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/DigesterJcrPropertyTest.java new file mode 100644 index 00000000..313fe170 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/jcrnodetype/DigesterJcrPropertyTest.java @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.jcrnodetype; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.OcmTestProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterJcrPropertyTest extends DigesterRepositoryTestBase { + private final static Logger log = LoggerFactory.getLogger(DigesterJcrPropertyTest.class); + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterJcrPropertyTest.class); + } + + public void testRequiredProperty() + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + //--------------------------------------------------------------------------------------------------------- + // Insert without the mandatory field + //--------------------------------------------------------------------------------------------------------- + + OcmTestProperty ocmTestProperty = new OcmTestProperty(); + ocmTestProperty.setPath("/test"); + ocmTestProperty.setRequiredProp("requiredPropValue"); + ocmTestProperty.setRequiredWithConstraintsProp("abc"); + + try + { + ocm.insert(ocmTestProperty); + fail("Incorrect insert operation - the mandatory fields have no value"); + } + catch(Exception e) + { + // Normal behaviour + ocm.refresh(false); + } + + //--------------------------------------------------------------------------------------------------------- + // Insert with the mandatory fields + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty.setMandatoryProp("mandatoryValue"); + ocmTestProperty.setMandatoryWithConstaintsProp("xx"); + ocm.insert(ocmTestProperty); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + assertTrue("Invalid required property", ocmTestProperty.getRequiredProp().equals("requiredPropValue")); + assertTrue("Invalid required property with constraints", ocmTestProperty.getRequiredWithConstraintsProp().equals("abc")); + assertTrue("Invalid autocreated property", ocmTestProperty.getAutoCreatedProp().equals("aaa")); + assertTrue("Invalid autocreated property", ocmTestProperty.getAutoCreatedWithConstraintsProp().equals("ccc")); + assertTrue("Invalid protected property", ocmTestProperty.getProtectedWithDefaultValueProp().equals("protectedValue")); + + //--------------------------------------------------------------------------------------------------------- + // update the property requiredWithConstraintsProp with bad value + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + ocmTestProperty.setRequiredWithConstraintsProp("invalid value"); + try + { + ocm.update(ocmTestProperty); + ocm.save(); + fail("Invalid value was accepted for requiredWithConstraintsProp"); + } + catch(Exception e) + { + // Do nothing - normal behaviour, the value + } + + //--------------------------------------------------------------------------------------------------------- + // update the property AutoCreatedWithConstraintsProp with bad value + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + ocmTestProperty.setAutoCreatedWithConstraintsProp("invalid value"); + try + { + ocm.update(ocmTestProperty); + ocm.save(); + fail("Invalid value was accepted for autoCreatedWithConstraintsProp "); + } + catch(Exception e) + { + // Do nothing - normal behaviour, the value is not valid + + } + + //--------------------------------------------------------------------------------------------------------- + // update the property mandatoryWithConstaintsProp with bad value + //--------------------------------------------------------------------------------------------------------- + ocmTestProperty = (OcmTestProperty) ocm.getObject("/test"); + ocmTestProperty.setMandatoryWithConstaintsProp("yy"); + try + { + ocm.update(ocmTestProperty); + ocm.save(); + fail("Invalid value was accepted for mandatoryWithConstaintsProp"); + } + catch(Exception e) + { + // expected; + } + + + } + catch (Exception e) + { + log.error("testRequiredProperty failed", e); + fail(); + } + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/lock/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/lock/AllTests.java new file mode 100644 index 00000000..3e5f28c5 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/lock/AllTests.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.lock; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.basic"); + //$JUnit-BEGIN$ + suite.addTestSuite(DigesterLockTest.class); + suite.addTestSuite(AnnotationLockTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/lock/AnnotationLockTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/lock/AnnotationLockTest.java new file mode 100644 index 00000000..6dbfd9ed --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/lock/AnnotationLockTest.java @@ -0,0 +1,231 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.lock; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.lock.Lock; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.Lockable; + +/** + * Test object content Manager lock feature + * + * @author Christophe Lombart + */ +public class AnnotationLockTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationLockTest.class); + } + + + public void testBasicLock() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Lock the object + // -------------------------------------------------------------------------------- + + Lock lock = ocm.lock("/test", true, false); + assertTrue("the Lock owner is not correct", lock.getLockOwner().equals(ocm.getSession().getUserID())); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertTrue("the object is not locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Unlock the object + // -------------------------------------------------------------------------------- + ocm.unlock("/test", lock.getLockToken()); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Lock & update + // -------------------------------------------------------------------------------- + lock = ocm.lock("/test", true, false); + a = (A) ocm.getObject("/test"); + a.setA1("new a1 Value"); + ocm.update(a); + ocm.save(); + ocm.unlock("/test", lock.getLockToken()); + + + // -------------------------------------------------------------------------------- + // Remove the object + // -------------------------------------------------------------------------------- + ocm.remove(a); + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Lock object which is assigned to a custome node type. This jcr node type inherits from mix:lockable + * + */ + public void testLockWithNodeType() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create an object which is associated to the + // -------------------------------------------------------------------------------- + Lockable lockable = new Lockable(); + lockable.setPath("/test"); + lockable.setA1("a1"); + lockable.setA2("a2"); + ocm.insert(lockable); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + lockable = (Lockable) ocm.getObject("/test"); + assertNotNull("a is null", lockable); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + assertNull("Attribute lockowner is not null", lockable.getLockOwner()); + // -------------------------------------------------------------------------------- + // Lock the object + // -------------------------------------------------------------------------------- + Lock lock = ocm.lock("/test", true, false); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertTrue("the object is not locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Unlock the object + // -------------------------------------------------------------------------------- + ocm.unlock("/test", lock.getLockToken()); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + + + // -------------------------------------------------------------------------------- + // Lock & update + // -------------------------------------------------------------------------------- + lock = ocm.lock("/test", true, false); + assertTrue("the object is not locked", ocm.isLocked("/test")); + lockable = (Lockable) ocm.getObject("/test"); + assertNotNull("Attribute lockowner is null", lockable.getLockOwner()); + lockable.setA1("new a1 Value"); + ocm.update(lockable); + ocm.save(); + ocm.unlock("/test", lock.getLockToken()); + + + // -------------------------------------------------------------------------------- + // Remove the object + // -------------------------------------------------------------------------------- + ocm.remove(lockable); + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/lock/DigesterLockTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/lock/DigesterLockTest.java new file mode 100644 index 00000000..4b416793 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/lock/DigesterLockTest.java @@ -0,0 +1,231 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.lock; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.lock.Lock; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.Lockable; + +/** + * Test object content Manager lock feature + * + * @author Christophe Lombart + */ +public class DigesterLockTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterLockTest.class); + } + + + public void testBasicLock() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object graph in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setA1("a1"); + a.setA2("a2"); + B b = new B(); + b.setB1("b1"); + b.setB2("b2"); + a.setB(b); + + C c1 = new C(); + c1.setId("first"); + c1.setName("First Element"); + C c2 = new C(); + c2.setId("second"); + c2.setName("Second Element"); + + C c3 = new C(); + c3.setId("third"); + c3.setName("Third Element"); + + + Collection collection = new ArrayList(); + collection.add(c1); + collection.add(c2); + collection.add(c3); + + a.setCollection(collection); + + ocm.insert(a); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Lock the object + // -------------------------------------------------------------------------------- + + Lock lock = ocm.lock("/test", true, false); + assertTrue("the Lock owner is not correct", lock.getLockOwner().equals(ocm.getSession().getUserID())); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertTrue("the object is not locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Unlock the object + // -------------------------------------------------------------------------------- + ocm.unlock("/test", lock.getLockToken()); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Lock & update + // -------------------------------------------------------------------------------- + lock = ocm.lock("/test", true, false); + a = (A) ocm.getObject("/test"); + a.setA1("new a1 Value"); + ocm.update(a); + ocm.save(); + ocm.unlock("/test", lock.getLockToken()); + + + // -------------------------------------------------------------------------------- + // Remove the object + // -------------------------------------------------------------------------------- + ocm.remove(a); + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Lock object which is assigned to a custome node type. This jcr node type inherits from mix:lockable + * + */ + public void testLockWithNodeType() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create an object which is associated to the + // -------------------------------------------------------------------------------- + Lockable lockable = new Lockable(); + lockable.setPath("/test"); + lockable.setA1("a1"); + lockable.setA2("a2"); + ocm.insert(lockable); + ocm.save(); + + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + lockable = (Lockable) ocm.getObject("/test"); + assertNotNull("a is null", lockable); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + assertNull("Attribute lockowner is not null", lockable.getLockOwner()); + // -------------------------------------------------------------------------------- + // Lock the object + // -------------------------------------------------------------------------------- + Lock lock = ocm.lock("/test", true, false); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertTrue("the object is not locked", ocm.isLocked("/test")); + + // -------------------------------------------------------------------------------- + // Unlock the object + // -------------------------------------------------------------------------------- + ocm.unlock("/test", lock.getLockToken()); + + // -------------------------------------------------------------------------------- + // Check if the object is locked + // -------------------------------------------------------------------------------- + assertFalse("the object is locked", ocm.isLocked("/test")); + + + // -------------------------------------------------------------------------------- + // Lock & update + // -------------------------------------------------------------------------------- + lock = ocm.lock("/test", true, false); + assertTrue("the object is not locked", ocm.isLocked("/test")); + lockable = (Lockable) ocm.getObject("/test"); + assertNotNull("Attribute lockowner is null", lockable.getLockOwner()); + lockable.setA1("new a1 Value"); + ocm.update(lockable); + ocm.save(); + ocm.unlock("/test", lock.getLockToken()); + + + // -------------------------------------------------------------------------------- + // Remove the object + // -------------------------------------------------------------------------------- + ocm.remove(lockable); + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/AllTests.java new file mode 100644 index 00000000..a240b2f4 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/AllTests.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.proxy; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.proxy"); + //$JUnit-BEGIN$ + suite.addTestSuite(DigesterProxyTest.class); + suite.addTestSuite(AnnotationProxyTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/AnnotationProxyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/AnnotationProxyTest.java new file mode 100644 index 00000000..179dfba6 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/AnnotationProxyTest.java @@ -0,0 +1,267 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.proxy; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.proxy.Detail; +import org.apache.jackrabbit.ocm.testmodel.proxy.Main; +import org.apache.jackrabbit.ocm.testmodel.proxy.NTDetail; +import org.apache.jackrabbit.ocm.testmodel.proxy.NTMain; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class AnnotationProxyTest extends AnnotationRepositoryTestBase { + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationProxyTest.class); + } + + + public void testBeanProxy() { + + try { + ObjectContentManager ocm = getObjectContentManager(); + + Detail detail = new Detail(); + detail.setField("FieldValue"); + + Detail proxyDetail = new Detail(); + proxyDetail.setField("ProxyFieldValue"); + + Main main = new Main(); + main.setPath("/test"); + main.setDetail(detail); + main.setProxyDetail(proxyDetail); + + ocm.insert(main); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("detail is null", main.getDetail()); + assertTrue("Invalid detail bean", main.getDetail().getField().equals("FieldValue")); + + assertNotNull("proxydetail is null", main.getProxyDetail()); + Object proxyObject = main.getProxyDetail(); + assertTrue("Invalid class specify for the proxy bean", proxyObject instanceof Detail); + assertTrue("Invalid proxy detail bean",proxyDetail .getField().equals("ProxyFieldValue")); + + Detail nullDetail = main.getNullDetail(); + assertNull("nulldetail is not null",nullDetail ); + + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + detail = new Detail(); + detail.setField("AnotherFieldValue"); + + proxyDetail = new Detail(); + proxyDetail.setField("AnotherProxyFieldValue"); + + main.setDetail(detail); + main.setProxyDetail(proxyDetail); + + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("detail is null", main.getDetail()); + assertTrue("Invalid detail bean", main.getDetail().getField().equals("AnotherFieldValue")); + + assertNotNull("proxydetail is null", main.getProxyDetail()); + proxyObject = main.getProxyDetail(); + assertTrue("Invalid class specify for the proxy bean", proxyObject instanceof Detail); + assertTrue("Invalid proxy detail bean",proxyDetail .getField().equals("AnotherProxyFieldValue")); + + assertNull("nulldetail is not null",main.getNullDetail()); + + //--------------------------------------------------------------------------------------------------------- + // Delete the main object + //--------------------------------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + public void testDefaultCollectionConverterWithProxy() { + + try { + ObjectContentManager ocm = getObjectContentManager(); + + ArrayList details= new ArrayList(); + for(int i=1; i<=100;i++) + { + Detail detail = new Detail(); + detail.setField("field" + i); + details.add(detail); + } + + Main main = new Main(); + main.setProxyCollection(details); + main.setPath("/test"); + ocm.insert(main); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("main is null", main); + + Collection result = main.getProxyCollection(); + assertEquals("Invalide size", result.size(), 100); + assertNull("nullcollectionproxy is not null", main.getNullProxyCollection()); + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + + Detail detail = new Detail(); + detail.setField("newFieldValue"); + result.add(detail); + main.setProxyCollection(result); + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject("/test"); + assertNotNull("main is null", main); + assertEquals("Invalide size",main.getProxyCollection().size(), 101); + assertNull("nullcollectionproxy is not null", main.getNullProxyCollection()); + + //--------------------------------------------------------------------------------------------------------- + // Delete the main object + //--------------------------------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + + public void testNTCollectionconverterWithProxy() { + + try { + + ObjectContentManager ocm = getObjectContentManager(); + + NTMain main = new NTMain(); + main.setPath("/test"); + ocm.insert(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (NTMain) ocm.getObject( "/test"); + assertNotNull("main is null", main); + + Collection result = main.getProxyCollection(); + assertNull("Collection is not null", result); + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + ArrayList details= new ArrayList(); + for(int i=1; i<=100;i++) + { + NTDetail detail = new NTDetail(); + detail.setField("field" + i); + details.add(detail); + } + main.setProxyCollection(details); + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (NTMain) ocm.getObject( "/test"); + assertNotNull("main is null", main); + + result = main.getProxyCollection(); + assertEquals("Invalide size", result.size(), 100); + + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + NTDetail detail = new NTDetail(); + detail.setField("newFieldValue"); + result.add(detail); + main.setProxyCollection(result); + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (NTMain) ocm.getObject("/test"); + assertNotNull("main is null", main); + assertEquals("Invalide size",main.getProxyCollection().size(), 101); + + + //--------------------------------------------------------------------------------------------------------- + // Delete the main object + //--------------------------------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/DigesterProxyTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/DigesterProxyTest.java new file mode 100644 index 00000000..00edeb8b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/proxy/DigesterProxyTest.java @@ -0,0 +1,266 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.proxy; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.proxy.Detail; +import org.apache.jackrabbit.ocm.testmodel.proxy.Main; +import org.apache.jackrabbit.ocm.testmodel.proxy.NTDetail; +import org.apache.jackrabbit.ocm.testmodel.proxy.NTMain; + +/** + * Test inheritance with node type per concrete class (without discreminator field) + * + * @author Christophe Lombart + */ +public class DigesterProxyTest extends DigesterRepositoryTestBase { + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterProxyTest.class); + } + + public void testBeanProxy() { + + try { + ObjectContentManager ocm = getObjectContentManager(); + + Detail detail = new Detail(); + detail.setField("FieldValue"); + + Detail proxyDetail = new Detail(); + proxyDetail.setField("ProxyFieldValue"); + + Main main = new Main(); + main.setPath("/test"); + main.setDetail(detail); + main.setProxyDetail(proxyDetail); + + ocm.insert(main); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("detail is null", main.getDetail()); + assertTrue("Invalid detail bean", main.getDetail().getField().equals("FieldValue")); + + assertNotNull("proxydetail is null", main.getProxyDetail()); + Object proxyObject = main.getProxyDetail(); + assertTrue("Invalid class specify for the proxy bean", proxyObject instanceof Detail); + assertTrue("Invalid proxy detail bean",proxyDetail .getField().equals("ProxyFieldValue")); + + Detail nullDetail = main.getNullDetail(); + assertNull("nulldetail is not null",nullDetail ); + + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + detail = new Detail(); + detail.setField("AnotherFieldValue"); + + proxyDetail = new Detail(); + proxyDetail.setField("AnotherProxyFieldValue"); + + main.setDetail(detail); + main.setProxyDetail(proxyDetail); + + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("detail is null", main.getDetail()); + assertTrue("Invalid detail bean", main.getDetail().getField().equals("AnotherFieldValue")); + + assertNotNull("proxydetail is null", main.getProxyDetail()); + proxyObject = main.getProxyDetail(); + assertTrue("Invalid class specify for the proxy bean", proxyObject instanceof Detail); + assertTrue("Invalid proxy detail bean",proxyDetail .getField().equals("AnotherProxyFieldValue")); + + assertNull("nulldetail is not null",main.getNullDetail()); + + //--------------------------------------------------------------------------------------------------------- + // Delete the main object + //--------------------------------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + public void testDefaultCollectionConverterWithProxy() { + + try { + ObjectContentManager ocm = getObjectContentManager(); + + ArrayList details= new ArrayList(); + for(int i=1; i<=100;i++) + { + Detail detail = new Detail(); + detail.setField("field" + i); + details.add(detail); + } + + Main main = new Main(); + main.setProxyCollection(details); + main.setPath("/test"); + ocm.insert(main); + ocm.save(); + + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject( "/test"); + assertNotNull("main is null", main); + + Collection result = main.getProxyCollection(); + assertEquals("Invalide size", result.size(), 100); + assertNull("nullcollectionproxy is not null", main.getNullProxyCollection()); + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + + Detail detail = new Detail(); + detail.setField("newFieldValue"); + result.add(detail); + main.setProxyCollection(result); + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (Main) ocm.getObject("/test"); + assertNotNull("main is null", main); + assertEquals("Invalide size",main.getProxyCollection().size(), 101); + assertNull("nullcollectionproxy is not null", main.getNullProxyCollection()); + + //--------------------------------------------------------------------------------------------------------- + // Delete the main object + //--------------------------------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + + public void testNTCollectionconverterWithProxy() { + + try { + + ObjectContentManager ocm = getObjectContentManager(); + + NTMain main = new NTMain(); + main.setPath("/test"); + ocm.insert(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (NTMain) ocm.getObject( "/test"); + assertNotNull("main is null", main); + + Collection result = main.getProxyCollection(); + assertNull("Collection is not null", result); + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + ArrayList details= new ArrayList(); + for(int i=1; i<=100;i++) + { + NTDetail detail = new NTDetail(); + detail.setField("field" + i); + details.add(detail); + } + main.setProxyCollection(details); + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (NTMain) ocm.getObject( "/test"); + assertNotNull("main is null", main); + + result = main.getProxyCollection(); + assertEquals("Invalide size", result.size(), 100); + + + //--------------------------------------------------------------------------------------------------------- + // Update + //--------------------------------------------------------------------------------------------------------- + NTDetail detail = new NTDetail(); + detail.setField("newFieldValue"); + result.add(detail); + main.setProxyCollection(result); + ocm.update(main); + ocm.save(); + + //--------------------------------------------------------------------------------------------------------- + // Retrieve the main object + //--------------------------------------------------------------------------------------------------------- + main = (NTMain) ocm.getObject("/test"); + assertNotNull("main is null", main); + assertEquals("Invalide size",main.getProxyCollection().size(), 101); + + + //--------------------------------------------------------------------------------------------------------- + // Delete the main object + //--------------------------------------------------------------------------------------------------------- + ocm.remove("/test"); + ocm.save(); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + + } + + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AllTests.java new file mode 100644 index 00000000..1d0b805e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AllTests.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.query"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationAtomicQueryTest.class); + suite.addTestSuite(AnnotationIteratorQueryTest.class); + suite.addTestSuite(AnnotationMultiValueQueryTest.class); + suite.addTestSuite(AnnotationScopeQueryTest.class); + suite.addTestSuite(AnnotationSimpleQueryTest.class); + suite.addTestSuite(DigesterAtomicQueryTest.class); + suite.addTestSuite(DigesterIteratorQueryTest.class); + suite.addTestSuite(DigesterMultiValueQueryTest.class); + suite.addTestSuite(DigesterScopeQueryTest.class); + suite.addTestSuite(DigesterSimpleQueryTest.class); + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationAtomicQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationAtomicQueryTest.java new file mode 100644 index 00000000..b139dc59 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationAtomicQueryTest.java @@ -0,0 +1,249 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.io.ByteArrayInputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test Query on atomic fields + * + * @author Christophe Lombart + */ +public class AnnotationAtomicQueryTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationAtomicQueryTest.class); + private Date date = new Date(); + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationAtomicQueryTest.class); + } + + protected void setUp() throws Exception + { + super.setUp(); + this.importData(date); + } + + public void testQueryAtomicFields() + { + + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + // Test Boolean value + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Atomic.class); + filter.addEqualTo("booleanObject", new Boolean(true)); + Query query = queryManager.createQuery(filter); + + long start = System.currentTimeMillis(); + Collection result = ocm.getObjects(query); + log.info("getObjects : " + (System.currentTimeMillis() - start)); + + assertTrue("Invalid number of objects - should be = 50", result.size() == 50); + + filter = queryManager.createFilter(Atomic.class); + filter.addEqualTo("booleanPrimitive", new Boolean(false)); + query = queryManager.createQuery(filter); + + start = System.currentTimeMillis(); + result = ocm.getObjects(query); + log.info("getObjects 2 : " + (System.currentTimeMillis() - start)); + assertTrue("Invalid number of objects - should be = 0", result.size() == 0); + + + // Test int value + filter = queryManager.createFilter(Atomic.class); + filter.addBetween("integerObject", new Integer(0), new Integer(500)); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 5", result.size() == 5); + + filter = queryManager.createFilter(Atomic.class); + filter.addLessOrEqualThan("intPrimitive", new Integer(236)); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 36", result.size() == 36); + + + //Test Date & Calendar + filter = queryManager.createFilter(Atomic.class); + Calendar calendar = Calendar.getInstance(); + calendar.set(2012, Calendar.DECEMBER, 01); + filter.addLessThan("calendar", calendar); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 100 ", result.size() == 100); + + filter = queryManager.createFilter(Atomic.class); + calendar = Calendar.getInstance(); + calendar.set(1975, Calendar.DECEMBER, 01); + filter.addLessThan("calendar", calendar); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 0 ", result.size() == 0); + + filter = queryManager.createFilter(Atomic.class); + filter.addEqualTo("date", date); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 100 ", result.size() == 100); + + filter = queryManager.createFilter(Atomic.class); + filter.addBetween("date", date, new Date()); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 100 ", result.size() == 100); + + filter = queryManager.createFilter(Atomic.class); + filter.addGreaterThan("date", date); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 0 ", result.size() == 0); + + // Test contains method + filter = queryManager.createFilter(Atomic.class); + filter.addContains(".", "JCR"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 50 ", result.size() == 50); + + filter = queryManager.createFilter(Atomic.class); + filter.addContains("string", "JCR"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 50 ", result.size() == 50); + + filter = queryManager.createFilter(Atomic.class); + filter.addContains("string", "ocm"); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 0 ", result.size() == 0); + + + + } + catch (Exception e) + { + e.printStackTrace(); + fail(); + } + + } + + public void testQueryAtomicFieldsWithConverter() + { + ObjectContentManager ocm = getObjectContentManager(); + + // Test Boolean value + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Atomic.class); + filter.addEqualTo("int2boolean", new Boolean(true)); + Query query = queryManager.createQuery(filter); + + long start = System.currentTimeMillis(); + Collection result = ocm.getObjects(query); + log.info("getObjects : " + (System.currentTimeMillis() - start)); + + assertEquals(50, result.size()); + } + + private void importData(Date date) + { + try + { + + ObjectContentManager ocm = getObjectContentManager(); + + for (int i = 1; i <= 100; i++) + { + Atomic a = new Atomic(); + a.setPath("/test" + i); + a.setBooleanObject(new Boolean(i%2==0)); + a.setBooleanPrimitive(true); + a.setIntegerObject(new Integer(100 * i)); + a.setIntPrimitive(200 + i); + a.setDate(date); + Calendar calendar = Calendar.getInstance(); + calendar.set(1976, 4, 20, 15, 40); + a.setCalendar(calendar); + a.setDoubleObject(new Double(2.12 + i)); + a.setDoublePrimitive(1.23 + i); + long now = System.currentTimeMillis(); + a.setTimestamp(new Timestamp(now)); + if ((i % 2) == 0) + { + a.setString("Test String JCR " + i); + a.setByteArray("This is small object stored in a JCR repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Test inputstream".getBytes())); + a.setInt2boolean(true); + } + else + { + a.setByteArray("This is small object stored in the ocm repository".getBytes()); + a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); + a.setString("Test String " + i); + a.setInt2boolean(false); + } + ocm.insert(a); + + + } + ocm.save(); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationIteratorQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationIteratorQueryTest.java new file mode 100644 index 00000000..54eb0949 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationIteratorQueryTest.java @@ -0,0 +1,206 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectIterator; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Test Object Iterator + * + * @author Christophe Lombart + */ +public class AnnotationIteratorQueryTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationIteratorQueryTest.class); + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationIteratorQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + this.importData(); + + } + + /** + * Test equalTo + * + */ + public void testsetScope() + { + + try + { + + // No scope + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(Page.class); + Query query = queryManager.createQuery(filter); + // we need this to be sure about objects order in the iterator test + query.addOrderByAscending("title"); + ObjectContentManager ocm = this.getObjectContentManager(); + + long start = System.currentTimeMillis(); + ObjectIterator iterator = (ObjectIterator) ocm.getObjectIterator(query); + log.info("getObjectIterator takes : " + (System.currentTimeMillis() - start)); + + start = System.currentTimeMillis(); + Collection result = ocm.getObjects(query); + log.info("getObject takes : " + (System.currentTimeMillis() - start)); + + + start = System.currentTimeMillis(); + iterator = (ObjectIterator) ocm.getObjectIterator(query); + log.info("getObjectIterator takes : " + (System.currentTimeMillis() - start)); + assertEquals("wrong results count", 4, iterator.getSize()); + assertEquals("wrong initial position", 0, iterator.getPosition()); + assertTrue("no objects returned", iterator.hasNext()); + Page page = (Page) iterator.next(); + assertEquals("wrong first result", "Page 1 Title", page.getTitle()); + iterator.skip(1); + assertEquals("wrong position after skip", 2, iterator.getPosition()); + page = (Page) iterator.next(); + assertEquals("wrong third result", "Page 3 Title", page.getTitle()); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + private void importData() throws JcrMappingException + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + + if (ocm.objectExists("/test")) + { + ocm.remove("/test"); + } + + Session session = ocm.getSession(); + Node root = session.getRootNode(); + root.addNode("test"); + root.addNode("test/node1"); + root.addNode("test/node2"); + + session.save(); + + Page page = new Page(); + page.setPath("/test/node1/page1"); + page.setTitle("Page 1 Title"); + + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + paragraphs.add(new Paragraph("Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + + page = new Page(); + page.setPath("/test/node1/page2"); + page.setTitle("Page 2 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/test/node2/page1"); + page.setTitle("Page 3 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 4")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/test/node2/page2"); + page.setTitle("Page 4 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 6")); + paragraphs.add(new Paragraph("Para 7")); + paragraphs.add(new Paragraph("Para 8")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + ocm.save(); + + + + } + catch (RepositoryException e) + { + + e.printStackTrace(); + } + + + } +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerMultiValueQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationMultiValueQueryTest.java similarity index 50% rename from src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerMultiValueQueryTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationMultiValueQueryTest.java index 144a2ef9..4ea3e05d 100644 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerMultiValueQueryTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationMultiValueQueryTest.java @@ -1,61 +1,48 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.impl; +package org.apache.jackrabbit.ocm.manager.query; import java.util.ArrayList; import java.util.Collection; import javax.jcr.Node; import javax.jcr.Session; - import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.MultiValue; +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.MultiValue; /** * Test NTCollectionConverterImpl * * @author Christophe Lombart */ -public class PersistenceManagerMultiValueQueryTest extends TestBase +public class AnnotationMultiValueQueryTest extends AnnotationRepositoryTestBase { - private final static Log log = LogFactory.getLog(PersistenceManagerMultiValueQueryTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerMultiValueQueryTest(String testName) throws Exception - { - super(testName); - } public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerMultiValueQueryTest.class); + return new TestSuite(AnnotationMultiValueQueryTest.class); } /** @@ -65,50 +52,39 @@ protected void setUp() throws Exception { super.setUp(); this.importData(); - + } - - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - - } - getPersistenceManager().save(); - super.tearDown(); - } - + + public void testMultiValueSearch() { try { - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(MultiValue.class); + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(MultiValue.class); filter.addEqualTo("multiValues", "Value1"); - Query query = queryManager.createQuery(filter); - PersistenceManager persistenceManager = this.getPersistenceManager(); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 3", result.size() == 3); - - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(MultiValue.class); + Query query = queryManager.createQuery(filter); + ObjectContentManager ocm = this.getObjectContentManager(); + Collection result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 3", result.size() == 3); + + filter = queryManager.createFilter(MultiValue.class); filter.addEqualTo("multiValues", "Value9"); - query = queryManager.createQuery(filter); - persistenceManager = this.getPersistenceManager(); - result = persistenceManager.getObjects(query); + query = queryManager.createQuery(filter); + ocm = this.getObjectContentManager(); + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 1", result.size() == 1); MultiValue multiValue = (MultiValue)result.iterator().next(); assertTrue("Incorrect MultiValue found ", multiValue.getName().equals("m3")); - + } catch (Exception e) { e.printStackTrace(); fail("Exception occurs during the unit test : " + e); } - + } @@ -116,11 +92,9 @@ public void importData() { try { - PersistenceManager persistenceManager = getPersistenceManager(); + ObjectContentManager ocm = getObjectContentManager(); - PersistenceManagerImpl persistenceManagerImpl = (PersistenceManagerImpl) persistenceManager; - - Session session = persistenceManagerImpl.getSession(); + Session session = ocm.getSession(); Node root = session.getRootNode(); root.addNode("test"); @@ -133,8 +107,8 @@ public void importData() values.add("Value3"); values.add("Value4"); multiValue.setMultiValues(values); - persistenceManager.insert(multiValue); - + ocm.insert(multiValue); + multiValue = new MultiValue(); multiValue.setPath("/test/m2"); multiValue.setName("m2"); @@ -142,10 +116,10 @@ public void importData() values.add("Value1"); values.add("Value5"); values.add("Value6"); - values.add("Value7"); + values.add("Value7"); multiValue.setMultiValues(values); - persistenceManager.insert(multiValue); - + ocm.insert(multiValue); + multiValue = new MultiValue(); multiValue.setPath("/test/m3"); multiValue.setName("m3"); @@ -154,12 +128,12 @@ public void importData() values.add("Value2"); values.add("Value8"); values.add("Value9"); - + multiValue.setMultiValues(values); - persistenceManager.insert(multiValue); - - persistenceManager.save(); - + ocm.insert(multiValue); + + ocm.save(); + } catch(Exception e) { diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationScopeQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationScopeQueryTest.java new file mode 100644 index 00000000..290f2e67 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationScopeQueryTest.java @@ -0,0 +1,214 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + + +/** + * Test QueryManagerImpl Query methods + * + * @author Christophe Lombart + */ +public class AnnotationScopeQueryTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationScopeQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + this.importData(); + //this.importDocument("data.xml", "/"); + + + } + + + /** + * Test equalTo + * + */ + public void testsetScope() + { + + try + { + + + ObjectContentManager ocm = getObjectContentManager(); + // Search on subtree (test/node1) + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test/node1//"); + Query query = queryManager.createQuery(filter); + Collection result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 8", result.size() == 8); + + + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test//"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 16", result.size() == 16); + + // Test on children + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test/"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 0", result.size() == 0); + + // Search on scope and properties + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test//"); + filter.addEqualTo("text", "Para 1"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 3", result.size() == 3); + + + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test//"); + filter.addContains("text", "another"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 4", result.size() == 4); + + filter = queryManager.createFilter(Page.class); + filter.setScope("/test/node1/"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 2", result.size() == 2); + assertTrue ("Invalid object in the collection" , this.contains(result, "/test/node1/page1", Page.class)); + assertTrue ("Invalid object in the collection" , this.contains(result, "/test/node1/page2", Page.class)); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + private void importData() throws JcrMappingException + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + + Session session = ocm.getSession(); + Node root = session.getRootNode(); + root.addNode("test"); + root.addNode("test/node1"); + root.addNode("test/node2"); + + Page page = new Page(); + page.setPath("/test/node1/page1"); + page.setTitle("Page 1 Title"); + + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + paragraphs.add(new Paragraph("Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + + page = new Page(); + page.setPath("/test/node1/page2"); + page.setTitle("Page 2 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/test/node2/page1"); + page.setTitle("Page 3 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 4")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert( page); + + page = new Page(); + page.setPath("/test/node2/page2"); + page.setTitle("Page 4 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 6")); + paragraphs.add(new Paragraph("Para 7")); + paragraphs.add(new Paragraph("Para 8")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + ocm.save(); + + + } + catch (RepositoryException e) + { + + e.printStackTrace(); + } + + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationSimpleQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationSimpleQueryTest.java new file mode 100644 index 00000000..4f817462 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/AnnotationSimpleQueryTest.java @@ -0,0 +1,270 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + + +/** + * Test QueryManagerImpl Query methods + * + * @author Christophe Lombart + */ +public class AnnotationSimpleQueryTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationSimpleQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + importData(); + } + + + /** + * Test equalTo + * + */ + public void testGetObjectEqualsTo() + { + + try + { + + // Build the Query Object + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addEqualTo("text", "Para 1"); + + + Query query = queryManager.createQuery(filter); + + ObjectContentManager ocm = this.getObjectContentManager(); + Paragraph paragraph = (Paragraph) ocm.getObject(query); + assertNotNull("Object is null", paragraph); + assertTrue("Invalid paragraph found" , paragraph.getText().equals("Para 1")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Test equalTo + * + */ + public void testGetObjectsEqualsTo() + { + + try + { + + // Build the Query Object + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addEqualTo("text", "Para 1"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + + ObjectContentManager ocm = this.getObjectContentManager(); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 1", 1, result.size()); + Paragraph paragraph = (Paragraph) result.iterator().next(); + assertTrue("Invalid paragraph found" , paragraph.getText().equals("Para 1")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Test the like "like" expression + */ + public void testGetObjectsLike() + { + + try + { + + // Build the Query Object + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addLike("text", "Para%"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + + ObjectContentManager ocm = this.getObjectContentManager(); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 3")); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + /** + * Build an or expression between 2 filters + * + */ + public void testGetObjectsOr() + { + + try + { + + // Build the Query Object + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter1 = queryManager.createFilter(Paragraph.class); + filter1.addEqualTo("text", "Para 1"); + filter1.setScope("/test/"); + + Filter filter2 = queryManager.createFilter(Paragraph.class); + filter2.addEqualTo("text", "Para 2"); + + filter1.addOrFilter(filter2); + + Query query = queryManager.createQuery(filter1); + + ObjectContentManager ocm = this.getObjectContentManager(); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 2", 2, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + public void testGetObjectOrderBy() + { + + try + { + + // Build the Query Object + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addLike("text", "Para%"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + query.addOrderByDescending("text"); + + ObjectContentManager ocm = this.getObjectContentManager(); + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 3")); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + private void importData() throws JcrMappingException + { + ObjectContentManager ocm = getObjectContentManager(); + + Page page = new Page(); + page.setPath("/test"); + page.setTitle("Page Title"); + + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + paragraphs.add(new Paragraph("Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + ocm.save(); + + + } + + private boolean containsText(Paragraph[] paragraphs, String text) + { + + for (int i = 0; i < paragraphs.length; i++) + { + if (paragraphs[i].getText().equals(text)) + { + return true; + } + } + return false; + + } +} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerAtomicQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterAtomicQueryTest.java similarity index 56% rename from src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerAtomicQueryTest.java rename to src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterAtomicQueryTest.java index 86ea43b9..8478e97f 100644 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerAtomicQueryTest.java +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterAtomicQueryTest.java @@ -1,20 +1,20 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ======================================================================== */ -package org.apache.portals.graffito.jcr.persistence.impl; +package org.apache.jackrabbit.ocm.manager.query; import java.io.ByteArrayInputStream; import java.sql.Timestamp; @@ -25,162 +25,148 @@ import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.Atomic; +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Atomic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Test Query on atomic fields * * @author Christophe Lombart */ -public class PersistenceManagerAtomicQueryTest extends TestBase +public class DigesterAtomicQueryTest extends DigesterRepositoryTestBase { - private final static Log log = LogFactory.getLog(PersistenceManagerAtomicQueryTest.class); + private final static Logger log = LoggerFactory.getLogger(DigesterAtomicQueryTest.class); private Date date = new Date(); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerAtomicQueryTest(String testName) throws Exception - { - super(testName); - - } + public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerAtomicQueryTest.class); + return new TestSuite(DigesterAtomicQueryTest.class); } - - - public void tearDown() throws Exception - { - - for (int i = 1; i <= 100; i++) - { - if (getPersistenceManager().objectExists("/test" + i)) - { - getPersistenceManager().remove("/test" + i); - } - } - getPersistenceManager().save(); - super.tearDown(); - } - + protected void setUp() throws Exception + { + super.setUp(); + this.importData(date); + } public void testQueryAtomicFields() { try { - - this.importData(date); - PersistenceManager persistenceManager = this.getPersistenceManager(); - - // Test Boolean value - QueryManager queryManager = this.getQueryManager(); + + ObjectContentManager ocm = getObjectContentManager(); + + // Test Boolean value + QueryManager queryManager = ocm.getQueryManager(); Filter filter = queryManager.createFilter(Atomic.class); filter.addEqualTo("booleanObject", new Boolean(true)); Query query = queryManager.createQuery(filter); - + long start = System.currentTimeMillis(); - Collection result = persistenceManager.getObjects(query); - System.out.println("getObjects : " + (System.currentTimeMillis() - start)); - + Collection result = ocm.getObjects(query); + log.info("getObjects : " + (System.currentTimeMillis() - start)); + assertTrue("Invalid number of objects - should be = 50", result.size() == 50); - + filter = queryManager.createFilter(Atomic.class); filter.addEqualTo("booleanPrimitive", new Boolean(false)); query = queryManager.createQuery(filter); start = System.currentTimeMillis(); - result = persistenceManager.getObjects(query); - System.out.println("getObjects 2 : " + (System.currentTimeMillis() - start)); + result = ocm.getObjects(query); + log.info("getObjects 2 : " + (System.currentTimeMillis() - start)); assertTrue("Invalid number of objects - should be = 0", result.size() == 0); - - + + // Test int value filter = queryManager.createFilter(Atomic.class); filter.addBetween("integerObject", new Integer(0), new Integer(500)); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 5", result.size() == 5); - + filter = queryManager.createFilter(Atomic.class); filter.addLessOrEqualThan("intPrimitive", new Integer(236)); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 36", result.size() == 36); - + //Test Date & Calendar filter = queryManager.createFilter(Atomic.class); Calendar calendar = Calendar.getInstance(); - calendar.set(2012, 12, 01); + calendar.set(2012, Calendar.DECEMBER, 01); filter.addLessThan("calendar", calendar); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 100 ", result.size() == 100); filter = queryManager.createFilter(Atomic.class); calendar = Calendar.getInstance(); - calendar.set(1975, 12, 01); + calendar.set(1975, Calendar.DECEMBER, 01); filter.addLessThan("calendar", calendar); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 0 ", result.size() == 0); - - filter = queryManager.createFilter(Atomic.class); + + filter = queryManager.createFilter(Atomic.class); filter.addEqualTo("date", date); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 100 ", result.size() == 100); - filter = queryManager.createFilter(Atomic.class); + filter = queryManager.createFilter(Atomic.class); filter.addBetween("date", date, new Date()); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 100 ", result.size() == 100); - + + filter = queryManager.createFilter(Atomic.class); + filter.addGreaterThan("date", date); + query = queryManager.createQuery(filter); + + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 0 ", result.size() == 0); + // Test contains method - filter = queryManager.createFilter(Atomic.class); + filter = queryManager.createFilter(Atomic.class); filter.addContains(".", "JCR"); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 50 ", result.size() == 50); - - filter = queryManager.createFilter(Atomic.class); - filter.addContains("byteArray", "Graffito"); + + filter = queryManager.createFilter(Atomic.class); + filter.addContains("string", "JCR"); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 50 ", result.size() == 50); - - filter = queryManager.createFilter(Atomic.class); - filter.addContains("byteArray", "String"); + + filter = queryManager.createFilter(Atomic.class); + filter.addContains("string", "ocm"); query = queryManager.createQuery(filter); - - result = persistenceManager.getObjects(query); + + result = ocm.getObjects(query); assertTrue("Invalid number of objects - should be = 0 ", result.size() == 0); - + } catch (Exception e) { @@ -190,13 +176,30 @@ public void testQueryAtomicFields() } + public void testQueryAtomicFieldsWithConverter() + { + ObjectContentManager ocm = getObjectContentManager(); + + // Test Boolean value + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Atomic.class); + filter.addEqualTo("int2boolean", new Boolean(true)); + Query query = queryManager.createQuery(filter); + + long start = System.currentTimeMillis(); + Collection result = ocm.getObjects(query); + log.info("getObjects : " + (System.currentTimeMillis() - start)); + + assertEquals(50, result.size()); + } + private void importData(Date date) { try { - PersistenceManager persistenceManager = getPersistenceManager(); - + ObjectContentManager ocm = getObjectContentManager(); + for (int i = 1; i <= 100; i++) { Atomic a = new Atomic(); @@ -205,7 +208,6 @@ private void importData(Date date) a.setBooleanPrimitive(true); a.setIntegerObject(new Integer(100 * i)); a.setIntPrimitive(200 + i); - a.setString("Test String " + i); a.setDate(date); Calendar calendar = Calendar.getInstance(); calendar.set(1976, 4, 20, 15, 40); @@ -216,19 +218,23 @@ private void importData(Date date) a.setTimestamp(new Timestamp(now)); if ((i % 2) == 0) { + a.setString("Test String JCR " + i); a.setByteArray("This is small object stored in a JCR repository".getBytes()); a.setInputStream(new ByteArrayInputStream("Test inputstream".getBytes())); + a.setInt2boolean(true); } else { - a.setByteArray("This is small object stored in a Graffito repository".getBytes()); + a.setByteArray("This is small object stored in the ocm repository".getBytes()); a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); + a.setString("Test String " + i); + a.setInt2boolean(false); } - persistenceManager.insert(a); - - + ocm.insert(a); + + } - persistenceManager.save(); + ocm.save(); } catch (Exception e) @@ -238,5 +244,5 @@ private void importData(Date date) } } - + } \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterIteratorQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterIteratorQueryTest.java new file mode 100644 index 00000000..29fb6afe --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterIteratorQueryTest.java @@ -0,0 +1,199 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.manager.impl.ObjectContentManagerImpl; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Test Object Iterator + * + * @author Christophe Lombart + */ +public class DigesterIteratorQueryTest extends DigesterRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(DigesterIteratorQueryTest.class); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterIteratorQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + this.importData(); + + } + + + /** + * Test equalTo + * + */ + public void testsetScope() + { + + try + { + + // No scope + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(Page.class); + Query query = queryManager.createQuery(filter); + ObjectContentManager ocm = this.getObjectContentManager(); + + long start = System.currentTimeMillis(); + Iterator iterator = ocm.getObjectIterator(query); + log.info("getObject takes : " + (System.currentTimeMillis() - start)); + + start = System.currentTimeMillis(); + Collection result = ocm.getObjects(query); + log.info("getObject takes : " + (System.currentTimeMillis() - start)); + + start = System.currentTimeMillis(); + iterator = ocm.getObjectIterator(query); + log.info("getObject takes : " + (System.currentTimeMillis() - start)); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + private void importData() throws JcrMappingException + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + + if (ocm.objectExists("/test")) + { + ocm.remove("/test"); + } + + ObjectContentManagerImpl ocmImpl = (ObjectContentManagerImpl) ocm; + + Session session = ocmImpl.getSession(); + Node root = session.getRootNode(); + root.addNode("test"); + root.addNode("test/node1"); + root.addNode("test/node2"); + + session.save(); + + Page page = new Page(); + page.setPath("/test/node1/page1"); + page.setTitle("Page 1 Title"); + + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + paragraphs.add(new Paragraph("Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + + page = new Page(); + page.setPath("/test/node1/page2"); + page.setTitle("Page 2 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/test/node2/page1"); + page.setTitle("Page 3 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 4")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/test/node2/page2"); + page.setTitle("Page 4 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 6")); + paragraphs.add(new Paragraph("Para 7")); + paragraphs.add(new Paragraph("Para 8")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + ocm.save(); + + + + } + catch (RepositoryException e) + { + + e.printStackTrace(); + } + + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterMultiValueQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterMultiValueQueryTest.java new file mode 100644 index 00000000..919c9548 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterMultiValueQueryTest.java @@ -0,0 +1,144 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.jcr.Node; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.MultiValue; + +/** + * Test NTCollectionConverterImpl + * + * @author Christophe Lombart + */ +public class DigesterMultiValueQueryTest extends DigesterRepositoryTestBase +{ + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterMultiValueQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + this.importData(); + + } + + + public void testMultiValueSearch() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(MultiValue.class); + filter.addEqualTo("multiValues", "Value1"); + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 3", result.size() == 3); + + filter = queryManager.createFilter(MultiValue.class); + filter.addEqualTo("multiValues", "Value9"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 1", result.size() == 1); + MultiValue multiValue = (MultiValue)result.iterator().next(); + assertTrue("Incorrect MultiValue found ", multiValue.getName().equals("m3")); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + public void importData() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + Session session = ocm.getSession(); + Node root = session.getRootNode(); + root.addNode("test"); + + MultiValue multiValue = new MultiValue(); + multiValue.setPath("/test/m1"); + multiValue.setName("m1"); + ArrayList values = new ArrayList(); + values.add("Value1"); + values.add("Value2"); + values.add("Value3"); + values.add("Value4"); + multiValue.setMultiValues(values); + ocm.insert(multiValue); + + multiValue = new MultiValue(); + multiValue.setPath("/test/m2"); + multiValue.setName("m2"); + values = new ArrayList(); + values.add("Value1"); + values.add("Value5"); + values.add("Value6"); + values.add("Value7"); + multiValue.setMultiValues(values); + ocm.insert(multiValue); + + multiValue = new MultiValue(); + multiValue.setPath("/test/m3"); + multiValue.setName("m3"); + values = new ArrayList(); + values.add("Value1"); + values.add("Value2"); + values.add("Value8"); + values.add("Value9"); + + multiValue.setMultiValues(values); + ocm.insert(multiValue); + + ocm.save(); + + } + catch(Exception e) + { + e.printStackTrace(); + fail("Impossible to insert objects"); + } + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterScopeQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterScopeQueryTest.java new file mode 100644 index 00000000..9dc9bd9a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterScopeQueryTest.java @@ -0,0 +1,214 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.jcr.Node; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + + +/** + * Test QueryManagerImpl Query methods + * + * @author Christophe Lombart + */ +public class DigesterScopeQueryTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterScopeQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception + { + super.setUp(); + this.importData(); + //this.importDocument("data.xml", "/"); + + + } + + + /** + * Test equalTo + * + */ + public void testsetScope() + { + + try + { + + + ObjectContentManager ocm = this.getObjectContentManager(); + // Search on subtree (test/node1) + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test/node1//"); + Query query = queryManager.createQuery(filter); + Collection result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 8", result.size() == 8); + + + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test//"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 16", result.size() == 16); + + // Test on children + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test/"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 0", result.size() == 0); + + // Search on scope and properties + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test//"); + filter.addEqualTo("text", "Para 1"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 3", result.size() == 3); + + + filter = queryManager.createFilter(Paragraph.class); + filter.setScope("/test//"); + filter.addContains("text", "another"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 4", result.size() == 4); + + filter = queryManager.createFilter(Page.class); + filter.setScope("/test/node1/"); + query = queryManager.createQuery(filter); + result = ocm.getObjects(query); + assertTrue("Invalid number of objects - should be = 2", result.size() == 2); + assertTrue ("Invalid object in the collection" , this.contains(result, "/test/node1/page1", Page.class)); + assertTrue ("Invalid object in the collection" , this.contains(result, "/test/node1/page2", Page.class)); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + private void importData() throws JcrMappingException + { + + try + { + ObjectContentManager ocm = getObjectContentManager(); + + Session session = ocm.getSession(); + Node root = session.getRootNode(); + root.addNode("test"); + root.addNode("test/node1"); + root.addNode("test/node2"); + + Page page = new Page(); + page.setPath("/test/node1/page1"); + page.setTitle("Page 1 Title"); + + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + paragraphs.add(new Paragraph("Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + + page = new Page(); + page.setPath("/test/node1/page2"); + page.setTitle("Page 2 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/test/node2/page1"); + page.setTitle("Page 3 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 4")); + paragraphs.add(new Paragraph("Para 5")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert( page); + + page = new Page(); + page.setPath("/test/node2/page2"); + page.setTitle("Page 4 Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 6")); + paragraphs.add(new Paragraph("Para 7")); + paragraphs.add(new Paragraph("Para 8")); + paragraphs.add(new Paragraph("Another Para")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + ocm.save(); + + + } + catch (RepositoryException e) + { + + e.printStackTrace(); + } + + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterSimpleQueryTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterSimpleQueryTest.java new file mode 100644 index 00000000..6d245f90 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/query/DigesterSimpleQueryTest.java @@ -0,0 +1,462 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.query; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +import javax.jcr.Node; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.query.impl.QueryImpl; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; + +/** + * Test QueryManagerImpl Query methods + * + * @author Christophe + * Lombart + */ +public class DigesterSimpleQueryTest extends DigesterRepositoryTestBase { + + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterSimpleQueryTest.class); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + importData(); + } + + /** + * Test equalTo + * + */ + public void testGetObjectEqualsTo() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addEqualTo("text", "Para 1"); + + Query query = queryManager.createQuery(filter); + Paragraph paragraph = (Paragraph) ocm.getObject(query); + assertNotNull("Object is null", paragraph); + assertTrue("Invalid paragraph found", paragraph.getText().equals("Para 1")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Test equalTo + * + */ + public void testGetObjectsEqualsTo() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addEqualTo("text", "Para 1"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 1", 1, result.size()); + Paragraph paragraph = (Paragraph) result.iterator().next(); + assertTrue("Invalid paragraph found", paragraph.getText().equals("Para 1")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Test the like "like" expression + */ + public void testGetObjectsLike() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addLike("text", "Para%"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 3")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Build an or expression between 2 filters + * + */ + public void testGetObjectsOr() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter1 = queryManager.createFilter(Paragraph.class); + filter1.addEqualTo("text", "Para 1"); + filter1.setScope("/test/"); + + Filter filter2 = queryManager.createFilter(Paragraph.class); + filter2.addEqualTo("text", "Para 2"); + + filter1.addOrFilter(filter2); + + Query query = queryManager.createQuery(filter1); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 2", 2, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Build an or expression within a single filter + * @author Shrirang Edgaonkar + */ + public void testGetObjectsOrForSingleFilter() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter1 = queryManager.createFilter(Paragraph.class); + filter1.addOrFilter("text", new String[]{"Para 1","Para 2"}); + filter1.setScope("/test/"); + + Query query = queryManager.createQuery(filter1); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 2", 2, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Build an or expression within a single filter + * @author Shrirang Edgaonkar + */ + public void testGetObjectsOrWithAndForSingleFilter() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter1 = queryManager.createFilter(Paragraph.class); + filter1.addOrFilter("text", new String[]{"Para 1","Another Para "}).addLike("text", "Para%"); + filter1.setScope("/test/"); + + Query query = queryManager.createQuery(filter1); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 1", 1, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + //assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + public void testGetObjectOrderBy() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addLike("text", "Para%"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + query.addOrderByDescending("text"); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 1")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 2")); + assertTrue("Invalid paragraph found", this.containsText(paragraphs,"Para 3")); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + + public void testGetObjectOrderByWithUpdatableJCRExpression() { + + try { + + ObjectContentManager ocm = this.getObjectContentManager(); + // Build the Query Object + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(Paragraph.class); + filter.addLike("text", "Para%"); + filter.setScope("/test/"); + + Query query = queryManager.createQuery(filter); + query.addOrderByDescending("text"); + + String strQueryBuilderStringWithDescending = ((QueryImpl)query).getOrderByExpression(); + + Collection result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + + //Text is Descending + Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); + Iterator iterator = result.iterator(); + Paragraph para = (Paragraph)iterator.next(); + assertEquals("Para 3",para.getText()); + para = (Paragraph)iterator.next(); + assertEquals("Para 2",para.getText()); + para = (Paragraph)iterator.next(); + assertEquals("Para 1",para.getText()); + + //Text is Ascending + query = queryManager.createQuery(filter); + query.addOrderByAscending("text"); + + ocm = this.getObjectContentManager(); + result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + iterator = result.iterator(); + para = (Paragraph)iterator.next(); + assertEquals("Para 1",para.getText()); + para = (Paragraph)iterator.next(); + assertEquals("Para 2",para.getText()); + para = (Paragraph)iterator.next(); + assertEquals("Para 3",para.getText()); + + //Text is Descending + query = queryManager.createQuery(filter); + ((QueryImpl)query).addJCRExpression(strQueryBuilderStringWithDescending); + ocm = this.getObjectContentManager(); + result = ocm.getObjects(query); + assertEquals("Invalid number of objects - should be = 3", 3, result.size()); + iterator = result.iterator(); + para = (Paragraph)iterator.next(); + assertEquals("Para 3",para.getText()); + para = (Paragraph)iterator.next(); + assertEquals("Para 2",para.getText()); + para = (Paragraph)iterator.next(); + assertEquals("Para 1",para.getText()); + + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + + } + + public void testGetObjectsByClassNameAndPath() { + try { + ObjectContentManager ocm = this.getObjectContentManager(); + Collection result = ocm.getObjects(Page.class, "/test"); + assertEquals("Invalid number of objects", 1, result.size()); + + Page[] pages = (Page[]) result.toArray(new Page[result.size()]); + assertTrue("Invalid Page found", pages[0].getTitle().equals("Page Title")); + + result = ocm.getObjects(Page.class, "/folder/test"); + assertEquals("Invalid number of objects", 4, result.size()); + + result = ocm.getObjects(Page.class, "/folder"); + assertEquals("Invalid number of objects", 0, result.size()); + + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + } + + private void importData() throws JcrMappingException + { + try { + ObjectContentManager ocm = getObjectContentManager(); + + Page page = new Page(); + page.setPath("/test"); + page.setTitle("Page Title"); + + ArrayList paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1")); + paragraphs.add(new Paragraph("Para 2")); + paragraphs.add(new Paragraph("Para 3")); + paragraphs.add(new Paragraph("Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + //add an extra node with other page objects + Node root = ocm.getSession().getRootNode(); + root.addNode("folder"); + page = new Page(); + page.setPath("/folder/test"); + page.setTitle("Page Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 1.1")); + paragraphs.add(new Paragraph("Para 1.2")); + paragraphs.add(new Paragraph("Para 1.3")); + paragraphs.add(new Paragraph("1.Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/folder/test"); + page.setTitle("Page Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 2.1")); + paragraphs.add(new Paragraph("Para 2.2")); + paragraphs.add(new Paragraph("Para 2.3")); + paragraphs.add(new Paragraph("2.Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/folder/test"); + page.setTitle("Page Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 3.1")); + paragraphs.add(new Paragraph("Para 3.2")); + paragraphs.add(new Paragraph("Para 3.3")); + paragraphs.add(new Paragraph("3.Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + page = new Page(); + page.setPath("/folder/test"); + page.setTitle("Page Title"); + + paragraphs = new ArrayList(); + + paragraphs.add(new Paragraph("Para 4.1")); + paragraphs.add(new Paragraph("Para 4.2")); + paragraphs.add(new Paragraph("Para 4.3")); + paragraphs.add(new Paragraph("4.Another Para ")); + page.setParagraphs(paragraphs); + + ocm.insert(page); + + ocm.save(); + } + catch (Exception e) + { + fail("Impossible to create the data " + e); + } + } + + private boolean containsText(Paragraph[] paragraphs, String text) + { + + for (int i = 0; i < paragraphs.length; i++) + { + if (paragraphs[i].getText().equals(text)) + { + return true; + } + } + return false; + + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/simplemapping/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/simplemapping/AllTests.java new file mode 100644 index 00000000..ce4e48c0 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/simplemapping/AllTests.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.simplemapping; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.simplemapping"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationSimpleTest.class); + + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/simplemapping/AnnotationSimpleTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/simplemapping/AnnotationSimpleTest.java new file mode 100644 index 00000000..625c4d27 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/simplemapping/AnnotationSimpleTest.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.simplemapping; + + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.SimpleAnnotedClass; +import org.apache.jackrabbit.ocm.testmodel.SimpleInterface; + +/** + * Test atomic persistence fields + * + * @author Christophe Lombart + */ +public class AnnotationSimpleTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationSimpleTest.class); + } + + + public void testSimpleAnnotedClasses() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + SimpleAnnotedClass a = new SimpleAnnotedClass(); + a.setPath("/test"); + a.setTest("test"); + + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (SimpleAnnotedClass) ocm.getObject( "/test"); + assertNotNull("A is null", a); + assertEquals("Invalid value for test", "test", a.getTest()); + + // -------------------------------------------------------------------------------- + // Update + // -------------------------------------------------------------------------------- + a.setTest("another test"); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = null; + a = (SimpleAnnotedClass) ocm.getObject( "/test"); + assertNotNull("A is null", a); + assertEquals("Invalid value for test", "another test", a.getTest()); + + // -------------------------------------------------------------------------------- + // Search on the interface + // -------------------------------------------------------------------------------- + QueryManager queryManager = ocm.getQueryManager(); + Filter filter = queryManager.createFilter(SimpleInterface.class); + filter.addEqualTo("test", "another test"); + Query q = queryManager.createQuery(filter); + + Collection result = ocm.getObjects(q); + assertNotNull(result); + assertEquals("Invalid number of SimpleInterface found", 1, result.size()); + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/AllTests.java new file mode 100644 index 00000000..e81d06cb --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/AllTests.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.uuid; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.jcr.manager.uuid"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationUuidTest.class); + suite.addTestSuite(DigesterUuidTest.class); + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/AnnotationUuidTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/AnnotationUuidTest.java new file mode 100644 index 00000000..8b1d46cc --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/AnnotationUuidTest.java @@ -0,0 +1,557 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.uuid; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.uuid.A; +import org.apache.jackrabbit.ocm.testmodel.uuid.B; +import org.apache.jackrabbit.ocm.testmodel.uuid.B2; +import org.apache.jackrabbit.ocm.testmodel.uuid.Descendant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Test on UUID & references + * + * @author Christophe Lombart + */ +public class AnnotationUuidTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationUuidTest.class); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return + new TestSuite(AnnotationUuidTest.class); + } + + public void testCollectionOfBeanWithUuidNull() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + A a1 = new A(); + a1.setPath("/a1"); + a1.setStringData("testdata1"); + ocm.insert(a1); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository without references to A + // -------------------------------------------------------------------------------- + B2 b = new B2(); + b.setPath("/testB2"); + + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + Collection allref = b.getMultiReferences(); + assertNull("collection is not null", allref); + + // -------------------------------------------------------------------------------- + // Update object B with a collection of A (UUID on A) + // -------------------------------------------------------------------------------- + ArrayList list = new ArrayList(); + list.add(a1); + b.setMultiReferences(list); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + assertNotNull("a is not null", b.getMultiReferences()); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * + * Map the jcr uuid into a String attribute + * + */ + public void testUuid() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setStringData("testdata"); + ocm.insert(a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setStringData("testdata2"); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test"); + assertNotNull("a is null", a); + assertTrue("The uuid has been modified", uuidA.equals(a.getUuid())); + + // -------------------------------------------------------------------------------- + // Get the object with the uuid + // -------------------------------------------------------------------------------- + a = (A) ocm.getObjectByUuid(uuidA); + assertNotNull("a is null", a); + assertTrue("Invalid object found with the uuid ", "testdata2".equals(a.getStringData())); + + // -------------------------------------------------------------------------------- + // Get the object with an invalid uuid + // -------------------------------------------------------------------------------- + try + { + a = (A) ocm.getObjectByUuid("1234"); + fail("Exception not throw"); + } + catch(Exception e) + { + //Throws an exception due to an invalid uuid + log.info("Invalid uuid : " + e); + + } + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + /** + * + * Map a Reference into a String attribute. + * Object B has an attribute containing the object A uuid. + * + */ + public void testFieldReference() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setStringData("testdata"); + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a reference to A + // -------------------------------------------------------------------------------- + B b = new B(); + b.setReference2A(uuidA); + b.setPath("/testB"); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve the object B with an invalid reference + // -------------------------------------------------------------------------------- + b = (B) ocm.getObject("/testB"); + assertNotNull("b is null", b); + assertTrue("Invalid uuid property", b.getReference2A().equals(uuidA)); + + // -------------------------------------------------------------------------------- + // Update the object B with an invalid reference + // -------------------------------------------------------------------------------- + b.setReference2A("1245"); + try + { + ocm.update(b); + fail("Exception not throw"); + } + catch(Exception e) + { + //Throws an exception due to an invalid uuid + log.info("Invalid uuid : " + e); + + } + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * + * Map a Reference into a bean attribute. + * Object B has an attribute containing the object A. + * The jcr node matching to the object B contains a reference (the jcr node matching to the object B). + * + */ + public void testBeanReference() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setStringData("testdata"); + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object a + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a reference to A + // -------------------------------------------------------------------------------- + B2 b = new B2(); + b.setA(a); + b.setPath("/testB2"); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + a = b.getA(); + assertNotNull("a is null", a); + assertTrue("Invalid object a", a.getStringData().equals("testdata")); + assertTrue("Invalid uuid property", a.getUuid().equals(uuidA)); + + // -------------------------------------------------------------------------------- + // Update object B with an null value + // -------------------------------------------------------------------------------- + b.setA(null); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + a = b.getA(); + assertNull("a is not null", a); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Map a list of uuid into a collection of String + * The list is defined in a jcr property (Referece type / multi values) + * + */ + public void testCollectionOfUuid() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a1 = new A(); + a1.setPath("/a1"); + a1.setStringData("testdata1"); + ocm.insert(a1); + + A a2 = new A(); + a2.setPath("/a2"); + a2.setStringData("testdata2"); + ocm.insert(a2); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the objects + // -------------------------------------------------------------------------------- + a1 = (A) ocm.getObject( "/a1"); + assertNotNull("a1 is null", a1); + a2 = (A) ocm.getObject( "/a2"); + assertNotNull("a2 is null", a2); + ArrayList references = new ArrayList(); + references.add(a1.getUuid()); + references.add(a2.getUuid()); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a collection of A + // -------------------------------------------------------------------------------- + B b = new B(); + b.setPath("/testB"); + b.setMultiReferences(references); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B) ocm.getObject("/testB"); + Collection allref = b.getMultiReferences(); + assertNotNull("collection is null", allref); + assertTrue("Invalid number of items in the collection", allref.size() == 2); + + // -------------------------------------------------------------------------------- + // Update object B with invalid uuid + // -------------------------------------------------------------------------------- + allref.add("12345"); + b.setMultiReferences(allref); + try + { + ocm.update(b); + fail("Exception not throw"); + } + catch(Exception e) + { + //Throws an exception due to an invalid uuid + log.info("Invalid uuid value in the collection : " + e); + + } + + // -------------------------------------------------------------------------------- + // Update object B with an null value + // -------------------------------------------------------------------------------- + b.setMultiReferences(null); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B) ocm.getObject("/testB"); + assertNull("a is not null", b.getMultiReferences()); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Map a list of uuid into a collection + * The list is defined in a jcr property (multi values) + * + */ + public void testCollectionOfBeanWithUuid() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a1 = new A(); + a1.setPath("/a1"); + a1.setStringData("testdata1"); + ocm.insert(a1); + + A a2 = new A(); + a2.setPath("/a2"); + a2.setStringData("testdata2"); + ocm.insert(a2); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the objects + // -------------------------------------------------------------------------------- + a1 = (A) ocm.getObject( "/a1"); + assertNotNull("a1 is null", a1); + a2 = (A) ocm.getObject( "/a2"); + assertNotNull("a2 is null", a2); + ArrayList references = new ArrayList(); + references.add(a1); + references.add(a2); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a collection of A + // -------------------------------------------------------------------------------- + B2 b = new B2(); + b.setPath("/testB2"); + b.setMultiReferences(references); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + Collection allref = b.getMultiReferences(); + assertNotNull("collection is null", allref); + assertTrue("Invalid number of items in the collection", allref.size() == 2); + this.contains(allref, "/a1" , A.class); + this.contains(allref, "/a2" , A.class); + + // -------------------------------------------------------------------------------- + // Update object B with an null value + // -------------------------------------------------------------------------------- + b.setMultiReferences(null); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + assertNull("a is not null", b.getMultiReferences()); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + /** + * Test on uuid field defined in an ancestor class + * + */ + public void testDescendantAncestor() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + Descendant a = new Descendant(); + a.setPath("/descendant"); + a.setStringData("testdata"); + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (Descendant) ocm.getObject( "/descendant"); + assertNotNull("a is null", a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setStringData("testdata2"); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (Descendant) ocm.getObject("/descendant"); + assertNotNull("a is null", a); + assertTrue("The uuid has been modified", uuidA.equals(a.getUuid())); + + // -------------------------------------------------------------------------------- + // Get the object with the uuid + // -------------------------------------------------------------------------------- + a = (Descendant) ocm.getObjectByUuid(uuidA); + assertNotNull("a is null", a); + assertTrue("Invalid object found with the uuid ", "testdata2".equals(a.getStringData())); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/DigesterUuidTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/DigesterUuidTest.java new file mode 100644 index 00000000..a8b04f6a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/uuid/DigesterUuidTest.java @@ -0,0 +1,505 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.uuid; + +import java.util.ArrayList; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.uuid.A; +import org.apache.jackrabbit.ocm.testmodel.uuid.B; +import org.apache.jackrabbit.ocm.testmodel.uuid.B2; +import org.apache.jackrabbit.ocm.testmodel.uuid.Descendant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Test on UUID & references + * + * @author Christophe Lombart + */ +public class DigesterUuidTest extends DigesterRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(DigesterUuidTest.class); + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterUuidTest.class); + } + + + /** + * + * Map the jcr uuid into a String attribute + * + */ + public void testUuid() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setStringData("testdata"); + ocm.insert(a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setStringData("testdata2"); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject("/test"); + assertNotNull("a is null", a); + assertTrue("The uuid has been modified", uuidA.equals(a.getUuid())); + + // -------------------------------------------------------------------------------- + // Get the object with the uuid + // -------------------------------------------------------------------------------- + a = (A) ocm.getObjectByUuid(uuidA); + assertNotNull("a is null", a); + assertTrue("Invalid object found with the uuid ", "testdata2".equals(a.getStringData())); + + // -------------------------------------------------------------------------------- + // Get the object with an invalid uuid + // -------------------------------------------------------------------------------- + try + { + a = (A) ocm.getObjectByUuid("1234"); + fail("Exception not throw"); + } + catch(Exception e) + { + //Throws an exception due to an invalid uuid + log.info("Invalid uuid : " + e); + } + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + /** + * + * Map a Reference into a String attribute. + * Object B has an attribute containing the object A uuid. + * + */ + public void testFieldReference() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setStringData("testdata"); + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a reference to A + // -------------------------------------------------------------------------------- + B b = new B(); + b.setReference2A(uuidA); + b.setPath("/testB"); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve the object B with an invalid reference + // -------------------------------------------------------------------------------- + b = (B) ocm.getObject("/testB"); + assertNotNull("b is null", b); + assertTrue("Invalid uuid property", b.getReference2A().equals(uuidA)); + + // -------------------------------------------------------------------------------- + // Update the object B with an invalid reference + // -------------------------------------------------------------------------------- + b.setReference2A("1245"); + try + { + ocm.update(b); + fail("Exception not throw"); + } + catch(Exception e) + { + //Throws an exception due to an invalid uuid + log.info("Invalid uuid : " + e); + + } + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * + * Map a Reference into a bean attribute. + * Object B has an attribute containing the object A. + * The jcr node matching to the object B contains a reference (the jcr node matching to the object B). + * + */ + public void testBeanReference() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a = new A(); + a.setPath("/test"); + a.setStringData("testdata"); + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object a + // -------------------------------------------------------------------------------- + a = (A) ocm.getObject( "/test"); + assertNotNull("a is null", a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a reference to A + // -------------------------------------------------------------------------------- + B2 b = new B2(); + b.setA(a); + b.setPath("/testB2"); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + a = b.getA(); + assertNotNull("a is null", a); + assertTrue("Invalid object a", a.getStringData().equals("testdata")); + assertTrue("Invalid uuid property", a.getUuid().equals(uuidA)); + + // -------------------------------------------------------------------------------- + // Update object B with an null value + // -------------------------------------------------------------------------------- + b.setA(null); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + a = b.getA(); + assertNull("a is not null", a); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Map a list of uuid into a collection of String + * The list is defined in a jcr property (Referece type / multi values) + * + */ + public void testCollectionOfUuid() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a1 = new A(); + a1.setPath("/a1"); + a1.setStringData("testdata1"); + ocm.insert(a1); + + A a2 = new A(); + a2.setPath("/a2"); + a2.setStringData("testdata2"); + ocm.insert(a2); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the objects + // -------------------------------------------------------------------------------- + a1 = (A) ocm.getObject( "/a1"); + assertNotNull("a1 is null", a1); + a2 = (A) ocm.getObject( "/a2"); + assertNotNull("a2 is null", a2); + ArrayList references = new ArrayList(); + references.add(a1.getUuid()); + references.add(a2.getUuid()); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a collection of A + // -------------------------------------------------------------------------------- + B b = new B(); + b.setPath("/testB"); + b.setMultiReferences(references); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B) ocm.getObject("/testB"); + Collection allref = b.getMultiReferences(); + assertNotNull("collection is null", allref); + assertTrue("Invalid number of items in the collection", allref.size() == 2); + + // -------------------------------------------------------------------------------- + // Update object B with invalid uuid + // -------------------------------------------------------------------------------- + allref.add("12345"); + b.setMultiReferences(allref); + try + { + ocm.update(b); + fail("Exception not throw"); + } + catch(Exception e) + { + //Throws an exception due to an invalid uuid + log.info("Invalid uuid value in the collection : " + e); + + } + + // -------------------------------------------------------------------------------- + // Update object B with an null value + // -------------------------------------------------------------------------------- + b.setMultiReferences(null); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B) ocm.getObject("/testB"); + assertNull("a is not null", b.getMultiReferences()); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + /** + * Map a list of uuid into a collection + * The list is defined in a jcr property (multi values) + * + */ + public void testCollectionOfBeanWithUuid() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + A a1 = new A(); + a1.setPath("/a1"); + a1.setStringData("testdata1"); + ocm.insert(a1); + + A a2 = new A(); + a2.setPath("/a2"); + a2.setStringData("testdata2"); + ocm.insert(a2); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the objects + // -------------------------------------------------------------------------------- + a1 = (A) ocm.getObject( "/a1"); + assertNotNull("a1 is null", a1); + a2 = (A) ocm.getObject( "/a2"); + assertNotNull("a2 is null", a2); + ArrayList references = new ArrayList(); + references.add(a1); + references.add(a2); + + // -------------------------------------------------------------------------------- + // Create and store an object B in the repository which has a collection of A + // -------------------------------------------------------------------------------- + B2 b = new B2(); + b.setPath("/testB2"); + b.setMultiReferences(references); + ocm.insert(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + Collection allref = b.getMultiReferences(); + assertNotNull("collection is null", allref); + assertTrue("Invalid number of items in the collection", allref.size() == 2); + this.contains(allref, "/a1" , A.class); + this.contains(allref, "/a2" , A.class); + + // -------------------------------------------------------------------------------- + // Update object B with an null value + // -------------------------------------------------------------------------------- + b.setMultiReferences(null); + ocm.update(b); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Retrieve object B + // -------------------------------------------------------------------------------- + b = (B2) ocm.getObject("/testB2"); + assertNull("a is not null", b.getMultiReferences()); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + + /** + * Test on uuid field defined in an ancestor class + * + */ + public void testDescendantAncestor() + { + try + { + ObjectContentManager ocm = getObjectContentManager(); + + + // -------------------------------------------------------------------------------- + // Create and store an object A in the repository + // -------------------------------------------------------------------------------- + Descendant a = new Descendant(); + a.setPath("/descendant"); + a.setStringData("testdata"); + ocm.insert(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (Descendant) ocm.getObject( "/descendant"); + assertNotNull("a is null", a); + String uuidA = a.getUuid(); + assertNotNull("uuid is null", uuidA); + log.info("UUID : " + uuidA); + + // -------------------------------------------------------------------------------- + // Update the object + // -------------------------------------------------------------------------------- + a.setStringData("testdata2"); + ocm.update(a); + ocm.save(); + + // -------------------------------------------------------------------------------- + // Get the object + // -------------------------------------------------------------------------------- + a = (Descendant) ocm.getObject("/descendant"); + assertNotNull("a is null", a); + assertTrue("The uuid has been modified", uuidA.equals(a.getUuid())); + + // -------------------------------------------------------------------------------- + // Get the object with the uuid + // -------------------------------------------------------------------------------- + a = (Descendant) ocm.getObjectByUuid(uuidA); + assertNotNull("a is null", a); + assertTrue("Invalid object found with the uuid ", "testdata2".equals(a.getStringData())); + + + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/version/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/manager/version/AllTests.java new file mode 100644 index 00000000..619928eb --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/version/AllTests.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.version; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.manager.version"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationBasicVersionningTest.class); + suite.addTestSuite(DigesterBasicVersionningTest.class); + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/version/AnnotationBasicVersionningTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/version/AnnotationBasicVersionningTest.java new file mode 100644 index 00000000..6c8719ce --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/version/AnnotationBasicVersionningTest.java @@ -0,0 +1,328 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.version; + + +import java.util.Date; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.testmodel.unstructured.UnstructuredPage; +import org.apache.jackrabbit.ocm.testmodel.unstructured.UnstructuredParagraph; +import org.apache.jackrabbit.ocm.testmodel.version.Author; +import org.apache.jackrabbit.ocm.testmodel.version.PressRelease; +import org.apache.jackrabbit.ocm.version.Version; +import org.apache.jackrabbit.ocm.version.VersionIterator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test Query on atomic fields + * + * @author Christophe Lombart + */ +public class AnnotationBasicVersionningTest extends AnnotationRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(AnnotationBasicVersionningTest.class); + + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationBasicVersionningTest.class); + } + + + public void testSimpleVersionWithNodeType() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + Page page = new Page(); + page.setPath("/page"); + page.setTitle("Page Title"); + page.addParagraph(new Paragraph("para1")); + page.addParagraph(new Paragraph("para2")); + ocm.insert(page); + ocm.save(); + + page.addParagraph(new Paragraph("para3")); + page.setTitle("Page Title 2"); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page"); + + page.addParagraph(new Paragraph("para4")); + page.setTitle("Page Title 3"); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page"); + + VersionIterator versionIterator = ocm.getAllVersions("/page"); + assertNotNull("VersionIterator is null", versionIterator); + assertTrue("Invalid number of versions found", versionIterator.getSize() == 3); + + while (versionIterator.hasNext()) + { + Version version = (Version) versionIterator.next(); + log.info("version found : "+ version.getName() + " - " + version.getPath() + " - " + version.getCreated().getTime()); + if (version.getName().equals("jcr:rootVersion")) + { + continue; + } + + page = (Page) ocm.getObject("/page", version.getName()); + assertNotNull("Page is null for version " + version.getName(), page); + + if (version.getName().equals("1.0")) + { + assertEquals("Invalid title for version " + version.getName(),page.getTitle(), "Page Title 2"); + } + + if (version.getName().equals("1.1")) + { + assertEquals("Invalid title for version " + version.getName(),page.getTitle(), "Page Title 3"); + } + + } + + Version baseVersion = ocm.getBaseVersion("/page"); + log.info("Base version : " + baseVersion.getName()); + + Version rootVersion = ocm.getRootVersion("/page"); + log.info("Root version : " + rootVersion.getName()); + //this.exportDocument("/home/christophe/export.xml", "/jcr:system/jcr:versionStorage", true, false); + + //Get the latest version + page = (Page) ocm.getObject( "/page"); + assertNotNull("Last version is nulll", page); + assertTrue("Invalid number of paragraph found in the last version", page.getParagraphs().size() == 4); + + + } + catch(Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + + } + } + + + public void testVersionLabels() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + Page page = new Page(); + page.setPath("/page"); + page.setTitle("Page Title"); + page.addParagraph(new Paragraph("para1")); + page.addParagraph(new Paragraph("para2")); + ocm.insert(page); + ocm.save(); + + + page.addParagraph(new Paragraph("para3")); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page", new String[] {"A", "B"}); + + page.addParagraph(new Paragraph("para4")); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page", new String[] {"C", "D"}); + + String[] allLabels = ocm.getAllVersionLabels("/page"); + assertTrue("Incorrect number of labels", allLabels.length == 4); + + String[] versionLabels = ocm.getVersionLabels("/page", "1.1"); + assertTrue("Incorrect number of labels", versionLabels.length == 2); + assertTrue("Incorrect label", versionLabels[0].equals("C") || versionLabels[0].equals("D")); + assertTrue("Incorrect label", versionLabels[1].equals("C") || versionLabels[1].equals("D")); + + + } + catch(Exception e) + { + e.printStackTrace(); + fail(); + } + } + + public void testSimpleVersionWithoutNodeType() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + UnstructuredPage page = new UnstructuredPage(); + page.setPath("/page"); + page.setTitle("Page Title"); + page.addParagraph(new UnstructuredParagraph("para1")); + page.addParagraph(new UnstructuredParagraph("para2")); + ocm.insert(page); + ocm.save(); + + + page.addParagraph(new UnstructuredParagraph("para3")); + page.setTitle("Page Title 2"); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page"); + + page.addParagraph(new UnstructuredParagraph("para4")); + page.setTitle("Page Title 3"); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page"); + + VersionIterator versionIterator = ocm.getAllVersions("/page"); + assertNotNull("VersionIterator is null", versionIterator); + assertTrue("Invalid number of versions found", versionIterator.getSize() == 3); + + while (versionIterator.hasNext()) + { + Version version = (Version) versionIterator.next(); + log.info("version found : "+ version.getName() + " - " + version.getPath() + " - " + version.getCreated().getTime()); + if (version.getName().equals("jcr:rootVersion")) + { + continue; + } + + page = (UnstructuredPage) ocm.getObject("/page", version.getName()); + + assertNotNull("Page is null for version " + version.getName(), page); + + if (version.getName().equals("1.0")) + { + assertEquals("Invalid title for version " + version.getName(),page.getTitle(), "Page Title 2"); + } + + if (version.getName().equals("1.1")) + { + assertEquals("Invalid title for version " + version.getName(),page.getTitle(), "Page Title 3"); + } + + } + + Version baseVersion = ocm.getBaseVersion("/page"); + log.info("Base version : " + baseVersion.getName()); + + Version rootVersion = ocm.getRootVersion("/page"); + log.info("Root version : " + rootVersion.getName()); + //this.exportDocument("/home/christophe/export.xml", "/jcr:system/jcr:versionStorage", true, false); + + //Get the latest version + page = (UnstructuredPage) ocm.getObject( "/page"); + assertNotNull("Last version is nulll", page); + assertTrue("Invalid number of paragraph found in the last version", page.getParagraphs().size() == 4); + + + } + catch(Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + + } + } + + public void testVersionedChild() { + ObjectContentManager ocm = getObjectContentManager(); + try { + + PressRelease pressRelease = new PressRelease(); + pressRelease.setContent("content v1"); + pressRelease.setPath("/pressrelease1"); + pressRelease.setPubDate(new Date()); + pressRelease.setTitle("Title"); + + Author author = new Author(); + author.setName("John"); + pressRelease.setAuthor(author); + ocm.insert(pressRelease); + ocm.save(); + + pressRelease.setContent("content v2"); + ocm.checkout("/pressrelease1"); + ocm.update(pressRelease); + ocm.save(); + ocm.checkin("/pressrelease1"); + + pressRelease.setContent("content v3"); + ocm.checkout("/pressrelease1"); + ocm.update(pressRelease); + ocm.save(); + ocm.checkin("/pressrelease1"); + + VersionIterator versionIterator = ocm + .getAllVersions("/pressrelease1"); + assertNotNull("VersionIterator is null", versionIterator); + assertTrue("Invalid number of versions found", versionIterator + .getSize() == 3); + + while (versionIterator.hasNext()) { + Version version = (Version) versionIterator.next(); + log.info("version found : " + version.getName() + " - " + + version.getPath() + " - " + + version.getCreated().getTime()); + if (version.getName().equals("jcr:rootVersion")) { + continue; + } + + pressRelease = (PressRelease) ocm.getObject("/pressrelease1", + version.getName()); + + assertNotNull("pressRelease is null for version " + + version.getName(), pressRelease); + + if (version.getName().equals("1.0")) { + assertEquals("Invalid content for version " + + version.getName(), pressRelease.getContent(), + "content v2"); + } + + if (version.getName().equals("1.1")) { + assertEquals("Invalid title for version " + + version.getName(), pressRelease.getContent(), + "content v3"); + } + + } + + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + + } + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/manager/version/DigesterBasicVersionningTest.java b/src/test/java/org/apache/jackrabbit/ocm/manager/version/DigesterBasicVersionningTest.java new file mode 100644 index 00000000..42440fd3 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/manager/version/DigesterBasicVersionningTest.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.manager.version; + + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.testmodel.Page; +import org.apache.jackrabbit.ocm.testmodel.Paragraph; +import org.apache.jackrabbit.ocm.version.Version; +import org.apache.jackrabbit.ocm.version.VersionIterator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test Query on atomic fields + * + * @author Christophe Lombart + */ +public class DigesterBasicVersionningTest extends DigesterRepositoryTestBase +{ + private final static Logger log = LoggerFactory.getLogger(DigesterBasicVersionningTest.class); + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterBasicVersionningTest.class); + } + + public void testSimpleVersion() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + Page page = new Page(); + page.setPath("/page"); + page.setTitle("Page Title"); + page.addParagraph(new Paragraph("para1")); + page.addParagraph(new Paragraph("para2")); + ocm.insert(page); + ocm.save(); + + page.addParagraph(new Paragraph("para3")); + page.setTitle("Page Title 2"); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page"); + + page.addParagraph(new Paragraph("para4")); + page.setTitle("Page Title 3"); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page"); + + VersionIterator versionIterator = ocm.getAllVersions("/page"); + assertNotNull("VersionIterator is null", versionIterator); + assertTrue("Invalid number of versions found", versionIterator.getSize() == 3); + + while (versionIterator.hasNext()) + { + Version version = (Version) versionIterator.next(); + log.info("version found : "+ version.getName() + " - " + version.getPath() + " - " + version.getCreated().getTime()); + if (version.getName().equals("jcr:rootVersion")) + { + continue; + } + + page = (Page) ocm.getObject("/page", version.getName()); + assertNotNull("Page is null for version " + version.getName(), page); + + if (version.getName().equals("1.0")) + { + assertEquals("Invalid title for version " + version.getName(),page.getTitle(), "Page Title 2"); + } + + if (version.getName().equals("1.1")) + { + assertEquals("Invalid title for version " + version.getName(),page.getTitle(), "Page Title 3"); + } + + } + + Version baseVersion = ocm.getBaseVersion("/page"); + log.info("Base version : " + baseVersion.getName()); + + Version rootVersion = ocm.getRootVersion("/page"); + log.info("Root version : " + rootVersion.getName()); + + //Get the latest version + page = (Page) ocm.getObject( "/page"); + assertNotNull("Last version is nulll", page); + assertTrue("Invalid number of paragraph found in the last version", page.getParagraphs().size() == 4); + + + } + catch(Exception e) + { + e.printStackTrace(); + fail(e.getMessage()); + + } + } + + + public void testVersionLabels() + { + ObjectContentManager ocm = getObjectContentManager(); + try + { + + Page page = new Page(); + page.setPath("/page"); + page.setTitle("Page Title"); + page.addParagraph(new Paragraph("para1")); + page.addParagraph(new Paragraph("para2")); + ocm.insert(page); + ocm.save(); + + + page.addParagraph(new Paragraph("para3")); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page", new String[] {"A", "B"}); + + page.addParagraph(new Paragraph("para4")); + ocm.checkout("/page"); + ocm.update(page); + ocm.save(); + ocm.checkin("/page", new String[] {"C", "D"}); + + String[] allLabels = ocm.getAllVersionLabels("/page"); + assertTrue("Incorrect number of labels", allLabels.length == 4); + + String[] versionLabels = ocm.getVersionLabels("/page", "1.1"); + assertTrue("Incorrect number of labels", versionLabels.length == 2); + assertTrue("Incorrect label", versionLabels[0].equals("C") || versionLabels[0].equals("D")); + assertTrue("Incorrect label", versionLabels[1].equals("C") || versionLabels[1].equals("D")); + + + } + catch(Exception e) + { + e.printStackTrace(); + fail(); + } + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/mapper/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/mapper/AllTests.java new file mode 100644 index 00000000..2d7eff21 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/mapper/AllTests.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.mapper"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationMapperImplTest.class); + suite.addTestSuite(DigesterMapperImplTest.class); + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/mapper/AnnotationMapperImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/mapper/AnnotationMapperImplTest.java new file mode 100644 index 00000000..83b9456a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/mapper/AnnotationMapperImplTest.java @@ -0,0 +1,582 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.AnnotationMapperImpl; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.OcmTestProperty; +import org.apache.jackrabbit.ocm.testmodel.SimpleAnnotedAbstractClass; +import org.apache.jackrabbit.ocm.testmodel.SimpleAnnotedClass; +import org.apache.jackrabbit.ocm.testmodel.SimpleInterface; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.CmsObjectImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Document; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; +import org.apache.jackrabbit.ocm.testmodel.proxy.Main; + +/** + * Test Annotation Mapper + * + * @author Christophe Lombart + */ +public class AnnotationMapperImplTest extends TestCase { + /** + *

Defines the test case name for junit.

+ * @param testName The test case name. + */ + public AnnotationMapperImplTest(String testName) { + super(testName); + } + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationMapperImplTest.class); + } + + /** + * Simple test mapper + * + */ + public void testMapper() { + try { + + Mapper mapper = getMapper(); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(A.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid classname", classDescriptor.getClassName().equals(A.class.getName())); + assertTrue("Invalid path field", classDescriptor.getPathFieldDescriptor().getFieldName().equals("path")); + assertEquals("Invalid mixins", "mix:lockable", classDescriptor.getJcrMixinTypes()[0]); + + FieldDescriptor fieldDescriptor = classDescriptor .getFieldDescriptor("a1"); + assertNotNull("FieldDescriptor is null", fieldDescriptor); + assertTrue("Invalid jcrName for field a1", fieldDescriptor.getJcrName().equals("a1")); + + BeanDescriptor beanDescriptor = classDescriptor.getBeanDescriptor("b"); + assertNotNull("BeanDescriptor is null", beanDescriptor); + assertTrue("Invalid jcrName for field b", beanDescriptor .getJcrName().equals("b")); + assertNotNull("Invalid bean default converter", beanDescriptor.getConverter()); + + + CollectionDescriptor collectionDescriptor = classDescriptor.getCollectionDescriptor("collection"); + assertNotNull("CollectionDescriptor is null", collectionDescriptor); + assertTrue("Invalid jcrName for field collection",collectionDescriptor.getJcrName().equals("collection")); + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + + /** + * Simple test mapper + * + */ + public void testUuid() { + try { + + Mapper mapper = getMapper(); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(org.apache.jackrabbit.ocm.testmodel.uuid.A.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid uuid field", classDescriptor.getUuidFieldDescriptor().getFieldName().equals("uuid")); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Simple test mapper + * + */ + public void testDiscriminatorSetting() { + try { + + Mapper mapper = getMapper(); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByNodeType("ocm:C"); + //ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(C.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid classname", classDescriptor.getClassName().equals(C.class.getName())); + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Test optional mapping properties + * + */ + public void testMapperOptionalProperties() { + try { + + Mapper mapper = getMapper(); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(B.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid classname", classDescriptor.getClassName() + .equals(B.class.getName())); + assertEquals(classDescriptor.getJcrSuperTypes(), "nt:base"); + + FieldDescriptor b1Field = classDescriptor.getFieldDescriptor("b1"); + assertNotNull("FieldDescriptor is null", b1Field); + assertEquals(b1Field.getFieldName(), "b1"); + assertEquals(b1Field.getJcrType(), "String"); + assertFalse(b1Field.isJcrAutoCreated()); + assertFalse(b1Field.isJcrMandatory()); + assertFalse(b1Field.isJcrProtected()); + assertFalse(b1Field.isJcrMultiple()); + assertEquals(b1Field.getJcrOnParentVersion(), "IGNORE"); + + FieldDescriptor b2Field = classDescriptor.getFieldDescriptor("b2"); + assertNotNull("FieldDescriptor is null", b2Field); + assertEquals(b2Field.getFieldName(), "b2"); + assertEquals(b2Field.getJcrType(), "String"); + assertFalse(b2Field.isJcrAutoCreated()); + assertFalse(b2Field.isJcrMandatory()); + assertFalse(b2Field.isJcrProtected()); + assertFalse(b2Field.isJcrMultiple()); + assertEquals(b2Field.getJcrOnParentVersion(), "IGNORE"); + + ClassDescriptor classDescriptor2 = mapper + .getClassDescriptorByClass(A.class); + assertNotNull("ClassDescriptor is null", classDescriptor2); + assertTrue("Invalid classname", classDescriptor2.getClassName() + .equals(A.class.getName())); + + BeanDescriptor beanDescriptor = classDescriptor2 + .getBeanDescriptor("b"); + assertNotNull(beanDescriptor); + assertEquals(beanDescriptor.getFieldName(), "b"); + assertEquals(beanDescriptor.getJcrType(), "nt:unstructured"); + assertFalse(beanDescriptor.isJcrAutoCreated()); + assertFalse(beanDescriptor.isJcrMandatory()); + assertFalse(beanDescriptor.isJcrProtected()); + assertFalse(beanDescriptor.isJcrSameNameSiblings()); + assertEquals(beanDescriptor.getJcrOnParentVersion(), "IGNORE"); + + CollectionDescriptor collectionDescriptor = classDescriptor2 + .getCollectionDescriptor("collection"); + assertNotNull(collectionDescriptor); + assertEquals(collectionDescriptor.getJcrType(), "nt:unstructured"); + assertFalse(collectionDescriptor.isJcrAutoCreated()); + assertFalse(collectionDescriptor.isJcrMandatory()); + assertFalse(collectionDescriptor.isJcrProtected()); + assertFalse(collectionDescriptor.isJcrSameNameSiblings()); + assertEquals(collectionDescriptor.getJcrOnParentVersion(), "IGNORE"); + + classDescriptor = mapper.getClassDescriptorByClass(OcmTestProperty.class); + assertNotNull(classDescriptor); + FieldDescriptor fieldDescriptor = classDescriptor.getFieldDescriptor("requiredWithConstraintsProp"); + assertNotNull(fieldDescriptor.getJcrValueConstraints()); + assertTrue("Invalid constaint", fieldDescriptor.getJcrValueConstraints()[0].equals("abc") ); + assertTrue("Invalid constaint", fieldDescriptor.getJcrValueConstraints()[1].equals("def") ); + assertTrue("Invalid constaint", fieldDescriptor.getJcrValueConstraints()[2].equals("ghi") ); + + fieldDescriptor = classDescriptor.getFieldDescriptor("autoCreatedProp"); + assertNotNull(fieldDescriptor.getJcrDefaultValue()); + assertTrue("Invalid default value", fieldDescriptor.getJcrDefaultValue().equals("aaa") ); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * + * Test Node Type per hierarchy setting + */ + public void testMapperNtHierarchy() { + try { + Mapper mapper = getMapper(); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper + .getClassDescriptorByClass(Ancestor.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertTrue("The ancestor class has no discriminator", + classDescriptor.hasDiscriminator()); + assertTrue("The ancestor class is not abstract", classDescriptor + .isAbstract()); + assertNull("The ancestor class has an ancestor", classDescriptor + .getSuperClassDescriptor()); + assertTrue( + "Ancestor class doesn't have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse( + "Ancestor class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + Collection descendandDescriptors = classDescriptor + .getDescendantClassDescriptors(); + assertEquals("Invalid number of descendants", descendandDescriptors + .size(), 2); + + classDescriptor = mapper.getClassDescriptorByClass(Descendant.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertTrue("The descendant class has no discriminator", + classDescriptor.hasDiscriminator()); + assertNotNull("ancerstorField is null in the descendant class", + classDescriptor.getFieldDescriptor("ancestorField")); + assertFalse("The descendant class is abstract", classDescriptor + .isAbstract()); + assertNotNull("The descendant class has not an ancestor", + classDescriptor.getSuperClassDescriptor()); + assertEquals("Invalid ancestor class for the descendant class", + classDescriptor.getSuperClassDescriptor().getClassName(), + "org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor"); + descendandDescriptors = classDescriptor + .getDescendantClassDescriptors(); + assertEquals("Invalid number of descendants", descendandDescriptors + .size(), 1); + assertTrue( + "Descendant class doesn't have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse( + "Descendant class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + classDescriptor = mapper.getClassDescriptorByClass(SubDescendant.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertTrue("The subdescendant class has no discriminator", + classDescriptor.hasDiscriminator()); + assertNotNull("ancestorField is null in the descendant class", + classDescriptor.getFieldDescriptor("ancestorField")); + assertFalse("The subdescendant class is abstract", classDescriptor + .isAbstract()); + assertNotNull("The subdescendant class has not an ancestor", + classDescriptor.getSuperClassDescriptor()); + assertEquals("Invalid ancestor class for the descendant class", + classDescriptor.getSuperClassDescriptor().getClassName(), + "org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant"); + descendandDescriptors = classDescriptor + .getDescendantClassDescriptors(); + assertEquals("Invalid number of descendants", descendandDescriptors + .size(), 0); + assertTrue( + "SubDescendant class doesn't have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse( + "SubDescendant class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * + * Test Node Type per concrete class setting + */ + public void testMapperNtConcreteClass() { + try { + Mapper mapper = getMapper(); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(CmsObjectImpl.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertFalse("The cms object class has discriminator", + classDescriptor.hasDiscriminator()); + assertTrue("The cmsobject class is not abstract", classDescriptor + .isAbstract()); + assertNull("The cmsobject class has an ancestor", classDescriptor + .getSuperClassDescriptor()); + assertFalse( + "The cmsobject class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue( + "The cmsobject class have not a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + assertTrue("The cmsobject class has no descendant ", + classDescriptor.hasDescendants()); + assertEquals("Invalid number of descendants", classDescriptor + .getDescendantClassDescriptors().size(), 2); + + classDescriptor = mapper.getClassDescriptorByClass(DocumentImpl.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertFalse("The document class has discriminator", + classDescriptor.hasDiscriminator()); + assertFalse("The document class is abstract", classDescriptor + .isAbstract()); + assertNotNull("The document class has not an ancestor", + classDescriptor.getSuperClassDescriptor()); + assertEquals("The document class has an invalid ancestor ancestor", + classDescriptor.getSuperClassDescriptor().getClassName(), + "org.apache.jackrabbit.ocm.testmodel.inheritance.impl.ContentImpl"); + assertFalse( + "The document class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue( + "The document class have not a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + assertFalse("The document class has no descendant ", + classDescriptor.hasDescendants()); + assertEquals("Invalid number of descendants", classDescriptor + .getDescendantClassDescriptors().size(), 0); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Test interface setting + */ + public void testInterfaceWithDiscriminator() { + try { + Mapper mapper = getMapper(); + assertNotNull("Mapper is null", mapper); + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(Interface.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertTrue("Interface is not an interface", classDescriptor.isInterface()); + assertTrue("Interface has not a discriminator", classDescriptor.hasDiscriminator()); + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin type for the interface",mixinTypes.length , 0); + assertNull("The interface has an ancestor", classDescriptor.getSuperClassDescriptor()); + assertTrue("The interface has not implementation/descendant", classDescriptor.hasDescendants()); + Collection descendants = classDescriptor.getDescendantClassDescriptors(); + assertEquals("Invalid number of implementation/descendants",2, descendants.size()); + //assertEquals("Invalid interface implementation",( (ClassDescriptor) descendants.iterator().next()).getClassName(), "org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant"); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse("Incalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + classDescriptor = mapper.getClassDescriptorByClass(AnotherDescendant.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertFalse("Interface is an interface", classDescriptor.isInterface()); + assertTrue("AnotherDescendant has not a discriminator", classDescriptor.hasDiscriminator()); + assertEquals("Invalid number of implemented interface", classDescriptor.getImplements().size(), 1); + assertEquals("Invalid interface name", classDescriptor.getImplements().iterator().next(), "org.apache.jackrabbit.ocm.testmodel.interfaces.Interface"); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Test interface setting + */ + public void testInterfaceWithoutDiscriminator() + { + try { + Mapper mapper = getMapper(); + assertNotNull("Mapper is null", mapper); + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(CmsObject.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertTrue("CmsObject is not an interface", classDescriptor.isInterface()); + assertFalse("Interface has a discriminator", classDescriptor.hasDiscriminator()); + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin type for the interface",mixinTypes.length , 0); + assertNull("The interface has an ancestor", classDescriptor.getSuperClassDescriptor()); + assertTrue("The interface has not implementation/descendant", classDescriptor.hasDescendants()); + Collection descendants = classDescriptor.getDescendantClassDescriptors(); + assertEquals("Invalid number of implementation/descendants", descendants.size(),3); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + + classDescriptor = mapper.getClassDescriptorByClass(Document.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertTrue("Document is not an interface", classDescriptor.isInterface()); + assertFalse("Document has a discriminator", classDescriptor.hasDiscriminator()); + assertEquals("Invalid number of implemented interface", classDescriptor.getImplements().size(), 1); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + descendants = classDescriptor.getDescendantClassDescriptors(); + assertEquals("Invalid number of implementation/descendants", descendants.size(),1); + + + classDescriptor = mapper.getClassDescriptorByClass(DocumentImpl.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertFalse("DocumentImpl is an interface", classDescriptor.isInterface()); + assertFalse("DocumentImpl has a discriminator", classDescriptor.hasDiscriminator()); + assertTrue("DocumentImpl has not interface", classDescriptor.hasInterfaces()); + assertEquals("Invalid number of implemented interface", classDescriptor.getImplements().size(), 1); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + public void testInheritanceWithMixin() + { + try { + Mapper mapper = getMapper(); + assertNotNull("Mapper is null", mapper); + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.Ancestor.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("No mixin defined for Ancestor", 1, classDescriptor.getJcrMixinTypes().length); + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin defined for Ancestor", "mix:referenceable", mixinTypes[0]); + + classDescriptor = mapper.getClassDescriptorByClass(org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.Descendant.class); + assertEquals("No mixin defined for Descendant", 1, classDescriptor.getJcrMixinTypes().length); + mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin defined for Ancestor", "mix:referenceable", mixinTypes[0]); + + classDescriptor = mapper.getClassDescriptorByClass(org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.SubDescendant.class); + assertEquals("No mixin defined for SubDescendant", 1, classDescriptor.getJcrMixinTypes().length); + mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin defined for Ancestor", "mix:referenceable", mixinTypes[0]); + + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * + * Test Node Type per concrete class setting + */ + public void testProxy() { + try { + Mapper mapper = getMapper(); + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(Main.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid proxy setting for bean field proxyDetail ", classDescriptor.getBeanDescriptor("proxyDetail").isProxy()); + assertFalse("Invalid proxy setting for bean field detail ", classDescriptor.getBeanDescriptor("detail").isProxy()); + assertTrue("Invalid proxy setting for collection field proxyDetail ", classDescriptor.getCollectionDescriptor("proxyCollection").isProxy()); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + public void testSimpleAnnotations() + { + try { + Mapper mapper = getMapper(); + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(SimpleAnnotedAbstractClass.class); + assertNotNull("ClassDescriptor for SimpleAnnotedAbstractClass is null", classDescriptor); + assertTrue("SimpleAnnotedAbstractClass is not Abstract ", classDescriptor.isAbstract()); + + classDescriptor = mapper.getClassDescriptorByClass(SimpleAnnotedClass.class); + assertNotNull("ClassDescriptor for SimpleAnnotedClass is null", classDescriptor); + assertFalse("SimpleAnnotedClass is Abstract ", classDescriptor.isAbstract()); + assertEquals("Invalid ancestor class for SimpleAnnotedClass ", + "org.apache.jackrabbit.ocm.testmodel.SimpleAnnotedAbstractClass", + classDescriptor.getSuperClassDescriptor().getClassName()); + assertEquals("Invalid number of implemented interface", 1, classDescriptor.getImplements().size()); + + String interfaceName = (String) classDescriptor.getImplements().iterator().next(); + assertEquals("Invalid interface for SimpleAnnotationClass", + "org.apache.jackrabbit.ocm.testmodel.SimpleInterface", + interfaceName); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to test simple annotation " + e); + } + } + + private Mapper getMapper() + { + List classes = new ArrayList(); + classes.add( org.apache.jackrabbit.ocm.testmodel.A.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.B.class); + classes.add( org.apache.jackrabbit.ocm.testmodel.C.class); + classes.add(OcmTestProperty.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant.class); + classes.add( org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.Ancestor.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.AnotherDescendant.class); + classes.add( org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.Descendant.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin.SubDescendant.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.impl.CmsObjectImpl.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.impl.FolderImpl.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.impl.ContentImpl.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.interfaces.Folder.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.interfaces.Content.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.interfaces.Document.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.interfaces.Interface.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.interfaces.AnotherInterface.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.proxy.Main.class); + classes.add(SimpleAnnotedAbstractClass.class); + classes.add(SimpleAnnotedClass.class); + classes.add(SimpleInterface.class); + classes.add(org.apache.jackrabbit.ocm.testmodel.uuid.A.class); + + Mapper mapper = new AnnotationMapperImpl(classes); + return mapper; + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/mapper/DigesterMapperImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/mapper/DigesterMapperImplTest.java new file mode 100644 index 00000000..33c55e2e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/mapper/DigesterMapperImplTest.java @@ -0,0 +1,507 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.mapper; + +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.exception.JcrMappingException; +import org.apache.jackrabbit.ocm.mapper.impl.digester.DigesterMapperImpl; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.testmodel.A; +import org.apache.jackrabbit.ocm.testmodel.B; +import org.apache.jackrabbit.ocm.testmodel.C; +import org.apache.jackrabbit.ocm.testmodel.OcmTestProperty; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor; +import org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.SubDescendant; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.CmsObjectImpl; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentImpl; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Document; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; +import org.apache.jackrabbit.ocm.testmodel.proxy.Main; + +/** + * Test Digester Mapper + * + * @author Christophe Lombart + */ +public class DigesterMapperImplTest extends TestCase { + /** + *

Defines the test case name for junit.

+ * @param testName The test case name. + */ + public DigesterMapperImplTest(String testName) { + super(testName); + } + + public static Test suite() { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterMapperImplTest.class); + } + + /** + * Simple test mapper + * + */ + public void testMapper() { + try { + + Mapper mapper = new DigesterMapperImpl( + "./src/test/test-config/jcrmapping-testdigester.xml"); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(A.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid classname", classDescriptor.getClassName().equals(A.class.getName())); + assertTrue("Invalid path field", classDescriptor.getPathFieldDescriptor().getFieldName().equals("path")); + assertEquals("Invalid mixins", "mixin:a", classDescriptor.getJcrMixinTypes()[0]); + + FieldDescriptor fieldDescriptor = classDescriptor .getFieldDescriptor("a1"); + assertNotNull("FieldDescriptor is null", fieldDescriptor); + assertTrue("Invalid jcrName for field a1", fieldDescriptor.getJcrName().equals("a1")); + + BeanDescriptor beanDescriptor = classDescriptor.getBeanDescriptor("b"); + assertNotNull("BeanDescriptor is null", beanDescriptor); + assertTrue("Invalid jcrName for field b", beanDescriptor .getJcrName().equals("b")); + assertNotNull("Invalid bean default converter", beanDescriptor.getConverter()); + + + CollectionDescriptor collectionDescriptor = classDescriptor.getCollectionDescriptor("collection"); + assertNotNull("CollectionDescriptor is null", collectionDescriptor); + assertTrue("Invalid jcrName for field collection",collectionDescriptor.getJcrName().equals("collection")); + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Simple test mapper + * + */ + public void testUuid() { + try { + + Mapper mapper = new DigesterMapperImpl( + "./src/test/test-config/jcrmapping-testdigester.xml"); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(org.apache.jackrabbit.ocm.testmodel.uuid.A.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid uuid field", classDescriptor.getUuidFieldDescriptor().getFieldName().equals("uuid")); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Simple test mapper + * + */ + public void testDiscriminatorSetting() { + try { + + Mapper mapper = new DigesterMapperImpl("./src/test/test-config/jcrmapping-testdigester.xml"); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByNodeType("ocm:C"); + //ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(C.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid classname", classDescriptor.getClassName().equals(C.class.getName())); + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Test optional mapping properties + * + */ + public void testMapperOptionalProperties() { + try { + + String[] files = { "./src/test/test-config/jcrmapping.xml", + "./src/test/test-config/jcrmapping-jcrnodetypes.xml"}; + + Mapper mapper = new DigesterMapperImpl(files); + + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(B.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid classname", classDescriptor.getClassName() + .equals(B.class.getName())); + assertEquals(classDescriptor.getJcrSuperTypes(), "nt:base"); + + FieldDescriptor b1Field = classDescriptor.getFieldDescriptor("b1"); + assertNotNull("FieldDescriptor is null", b1Field); + assertEquals(b1Field.getFieldName(), "b1"); + assertEquals(b1Field.getJcrType(), "String"); + assertFalse(b1Field.isJcrAutoCreated()); + assertFalse(b1Field.isJcrMandatory()); + assertFalse(b1Field.isJcrProtected()); + assertFalse(b1Field.isJcrMultiple()); + assertEquals(b1Field.getJcrOnParentVersion(), "IGNORE"); + + FieldDescriptor b2Field = classDescriptor.getFieldDescriptor("b2"); + assertNotNull("FieldDescriptor is null", b2Field); + assertEquals(b2Field.getFieldName(), "b2"); + assertEquals(b2Field.getJcrType(), "String"); + assertFalse(b2Field.isJcrAutoCreated()); + assertFalse(b2Field.isJcrMandatory()); + assertFalse(b2Field.isJcrProtected()); + assertFalse(b2Field.isJcrMultiple()); + assertEquals(b2Field.getJcrOnParentVersion(), "IGNORE"); + + ClassDescriptor classDescriptor2 = mapper + .getClassDescriptorByClass(A.class); + assertNotNull("ClassDescriptor is null", classDescriptor2); + assertTrue("Invalid classname", classDescriptor2.getClassName() + .equals(A.class.getName())); + + BeanDescriptor beanDescriptor = classDescriptor2 + .getBeanDescriptor("b"); + assertNotNull(beanDescriptor); + assertEquals(beanDescriptor.getFieldName(), "b"); + assertEquals(beanDescriptor.getJcrType(), "nt:unstructured"); + assertFalse(beanDescriptor.isJcrAutoCreated()); + assertFalse(beanDescriptor.isJcrMandatory()); + assertFalse(beanDescriptor.isJcrProtected()); + assertFalse(beanDescriptor.isJcrSameNameSiblings()); + assertEquals(beanDescriptor.getJcrOnParentVersion(), "IGNORE"); + + CollectionDescriptor collectionDescriptor = classDescriptor2 + .getCollectionDescriptor("collection"); + assertNotNull(collectionDescriptor); + assertEquals(collectionDescriptor.getJcrType(), "nt:unstructured"); + assertFalse(collectionDescriptor.isJcrAutoCreated()); + assertFalse(collectionDescriptor.isJcrMandatory()); + assertFalse(collectionDescriptor.isJcrProtected()); + assertFalse(collectionDescriptor.isJcrSameNameSiblings()); + assertEquals(collectionDescriptor.getJcrOnParentVersion(), "IGNORE"); + + classDescriptor = mapper.getClassDescriptorByClass(OcmTestProperty.class); + assertNotNull(classDescriptor); + FieldDescriptor fieldDescriptor = classDescriptor.getFieldDescriptor("requiredWithConstraintsProp"); + assertNotNull(fieldDescriptor.getJcrValueConstraints()); + assertTrue("Invalid constaint", fieldDescriptor.getJcrValueConstraints()[0].equals("abc") ); + assertTrue("Invalid constaint", fieldDescriptor.getJcrValueConstraints()[1].equals("def") ); + assertTrue("Invalid constaint", fieldDescriptor.getJcrValueConstraints()[2].equals("ghi") ); + + fieldDescriptor = classDescriptor.getFieldDescriptor("autoCreatedProp"); + assertNotNull(fieldDescriptor.getJcrDefaultValue()); + assertTrue("Invalid default value", fieldDescriptor.getJcrDefaultValue().equals("aaa") ); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * + * Test Node Type per hierarchy setting + */ + public void testMapperNtHierarchy() { + try { + String[] files = { "./src/test/test-config/jcrmapping.xml", + "./src/test/test-config/jcrmapping-atomic.xml", + "./src/test/test-config/jcrmapping-beandescriptor.xml", + "./src/test/test-config/jcrmapping-inheritance.xml" }; + + Mapper mapper = new DigesterMapperImpl(files); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper + .getClassDescriptorByClass(Ancestor.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertTrue("The ancestor class has no discriminator", + classDescriptor.hasDiscriminator()); + assertTrue("The ancestor class is not abstract", classDescriptor + .isAbstract()); + assertNull("The ancestor class has an ancestor", classDescriptor + .getSuperClassDescriptor()); + assertTrue( + "Ancestor class doesn't have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse( + "Ancestor class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + Collection descendandDescriptors = classDescriptor + .getDescendantClassDescriptors(); + assertEquals("Invalid number of descendants", descendandDescriptors + .size(), 2); + + classDescriptor = mapper.getClassDescriptorByClass(Descendant.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertTrue("The descendant class has no discriminator", + classDescriptor.hasDiscriminator()); + assertNotNull("ancerstorField is null in the descendant class", + classDescriptor.getFieldDescriptor("ancestorField")); + assertFalse("The descendant class is abstract", classDescriptor + .isAbstract()); + assertNotNull("The descendant class has not an ancestor", + classDescriptor.getSuperClassDescriptor()); + assertEquals("Invalid ancestor class for the descendant class", + classDescriptor.getSuperClassDescriptor().getClassName(), + "org.apache.jackrabbit.ocm.testmodel.inheritance.Ancestor"); + descendandDescriptors = classDescriptor + .getDescendantClassDescriptors(); + assertEquals("Invalid number of descendants", descendandDescriptors + .size(), 1); + assertTrue( + "Descendant class doesn't have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse( + "Descendant class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + classDescriptor = mapper.getClassDescriptorByClass(SubDescendant.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertTrue("The subdescendant class has no discriminator", + classDescriptor.hasDiscriminator()); + assertNotNull("ancestorField is null in the descendant class", + classDescriptor.getFieldDescriptor("ancestorField")); + assertFalse("The subdescendant class is abstract", classDescriptor + .isAbstract()); + assertNotNull("The subdescendant class has not an ancestor", + classDescriptor.getSuperClassDescriptor()); + assertEquals("Invalid ancestor class for the descendant class", + classDescriptor.getSuperClassDescriptor().getClassName(), + "org.apache.jackrabbit.ocm.testmodel.inheritance.Descendant"); + descendandDescriptors = classDescriptor + .getDescendantClassDescriptors(); + assertEquals("Invalid number of descendants", descendandDescriptors + .size(), 0); + assertTrue( + "SubDescendant class doesn't have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse( + "SubDescendant class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * + * Test Node Type per concrete class setting + */ + public void testMapperNtConcreteClass() { + try { + String[] files = { "./src/test/test-config/jcrmapping.xml", + "./src/test/test-config/jcrmapping-atomic.xml", + "./src/test/test-config/jcrmapping-beandescriptor.xml", + "./src/test/test-config/jcrmapping-inheritance.xml" }; + // String[] files = { "./src/test/test-config/jcrmapping-inheritance.xml"}; + + Mapper mapper = new DigesterMapperImpl(files); + + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(CmsObjectImpl.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertFalse("The cms object class has discriminator", + classDescriptor.hasDiscriminator()); + assertTrue("The cmsobject class is not abstract", classDescriptor + .isAbstract()); + assertNull("The cmsobject class has an ancestor", classDescriptor + .getSuperClassDescriptor()); + assertFalse( + "The cmsobject class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue( + "The cmsobject class have not a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + assertTrue("The cmsobject class has no descendant ", + classDescriptor.hasDescendants()); + assertEquals("Invalid number of descendants", classDescriptor + .getDescendantClassDescriptors().size(), 2); + + classDescriptor = mapper.getClassDescriptorByClass(DocumentImpl.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertEquals("Incorrect path field", classDescriptor + .getPathFieldDescriptor().getFieldName(), "path"); + assertFalse("The document class has discriminator", + classDescriptor.hasDiscriminator()); + assertFalse("The document class is abstract", classDescriptor + .isAbstract()); + assertNotNull("The document class has not an ancestor", + classDescriptor.getSuperClassDescriptor()); + assertEquals("The document class has an invalid ancestor ancestor", + classDescriptor.getSuperClassDescriptor().getClassName(), + "org.apache.jackrabbit.ocm.testmodel.inheritance.impl.ContentImpl"); + assertFalse( + "The document class have a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue( + "The document class have not a node type per hierarchy strategy", + classDescriptor.usesNodeTypePerConcreteClassStrategy()); + assertFalse("The document class has no descendant ", + classDescriptor.hasDescendants()); + assertEquals("Invalid number of descendants", classDescriptor + .getDescendantClassDescriptors().size(), 0); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Test interface setting + */ + public void testInterfaceWithDiscriminator() { + try { + String[] files = {"./src/test/test-config/jcrmapping-inheritance.xml"}; + Mapper mapper = new DigesterMapperImpl(files); + + assertNotNull("Mapper is null", mapper); + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(Interface.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertTrue("Interface is not an interface", classDescriptor.isInterface()); + assertTrue("Interface has not a discriminator", classDescriptor.hasDiscriminator()); + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin type for the interface",mixinTypes.length , 0); + assertNull("The interface has an ancestor", classDescriptor.getSuperClassDescriptor()); + assertTrue("The interface has not implementation/descendant", classDescriptor.hasDescendants()); + Collection descendants = classDescriptor.getDescendantClassDescriptors(); + assertEquals("Invalid number of implementation/descendants", descendants.size(), 1); + assertEquals("Invalid interface implementation",( (ClassDescriptor) descendants.iterator().next()).getClassName(), "org.apache.jackrabbit.ocm.testmodel.inheritance.AnotherDescendant"); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse("Incalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + classDescriptor = mapper.getClassDescriptorByClass(AnotherDescendant.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertFalse("Interface is an interface", classDescriptor.isInterface()); + assertTrue("AnotherDescendant has not a discriminator", classDescriptor.hasDiscriminator()); + assertEquals("Invalid number of implemented interface", classDescriptor.getImplements().size(), 1); + assertEquals("Invalid interface name", classDescriptor.getImplements().iterator().next(), "org.apache.jackrabbit.ocm.testmodel.interfaces.Interface"); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * Test interface setting + */ + public void testInterfaceWithoutDiscriminator() + { + try { + String[] files = {"./src/test/test-config/jcrmapping-inheritance.xml"}; + Mapper mapper = new DigesterMapperImpl(files); + + assertNotNull("Mapper is null", mapper); + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(CmsObject.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertTrue("CmsObject is not an interface", classDescriptor.isInterface()); + assertFalse("Interface has a discriminator", classDescriptor.hasDiscriminator()); + String[] mixinTypes = classDescriptor.getJcrMixinTypes(); + assertEquals("Invalid mixin type for the interface",mixinTypes.length , 0); + assertNull("The interface has an ancestor", classDescriptor.getSuperClassDescriptor()); + assertTrue("The interface has not implementation/descendant", classDescriptor.hasDescendants()); + Collection descendants = classDescriptor.getDescendantClassDescriptors(); + assertEquals("Invalid number of implementation/descendants", descendants.size(),3); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + + classDescriptor = mapper.getClassDescriptorByClass(Document.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertTrue("Document is not an interface", classDescriptor.isInterface()); + assertFalse("Document has a discriminator", classDescriptor.hasDiscriminator()); + assertEquals("Invalid number of implemented interface", classDescriptor.getImplements().size(), 0); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + descendants = classDescriptor.getDescendantClassDescriptors(); + assertEquals("Invalid number of implementation/descendants", descendants.size(),1); + + + classDescriptor = mapper.getClassDescriptorByClass(DocumentImpl.class); + assertNotNull("Classdescriptor is null", classDescriptor); + assertFalse("DocumentImpl is an interface", classDescriptor.isInterface()); + assertFalse("DocumentImpl has a discriminator", classDescriptor.hasDiscriminator()); + assertTrue("DocumentImpl has not interface", classDescriptor.hasInterfaces()); + assertEquals("Invalid number of implemented interface", classDescriptor.getImplements().size(), 1); + assertFalse("Invalid extend strategy", classDescriptor.usesNodeTypePerHierarchyStrategy()); + assertTrue("Invalid extend strategy", classDescriptor.usesNodeTypePerConcreteClassStrategy()); + + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + + /** + * + * Test Node Type per concrete class setting + */ + public void testProxy() { + try { + String[] files = { "./src/test/test-config/jcrmapping-proxy.xml" }; + + Mapper mapper = new DigesterMapperImpl(files); + assertNotNull("Mapper is null", mapper); + + ClassDescriptor classDescriptor = mapper.getClassDescriptorByClass(Main.class); + assertNotNull("ClassDescriptor is null", classDescriptor); + assertTrue("Invalid proxy setting for bean field proxyDetail ", classDescriptor.getBeanDescriptor("proxyDetail").isProxy()); + assertFalse("Invalid proxy setting for bean field detail ", classDescriptor.getBeanDescriptor("detail").isProxy()); + assertTrue("Invalid proxy setting for collection field proxyDetail ", classDescriptor.getCollectionDescriptor("proxyCollection").isProxy()); + + } catch (JcrMappingException e) { + e.printStackTrace(); + fail("Impossible to retrieve the converter " + e); + } + } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/nodemanagement/impl/NodeTypeManagerImplTest.java b/src/test/java/org/apache/jackrabbit/ocm/nodemanagement/impl/NodeTypeManagerImplTest.java new file mode 100644 index 00000000..5db9bad1 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/nodemanagement/impl/NodeTypeManagerImplTest.java @@ -0,0 +1,618 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.nodemanagement.impl; + +import java.io.IOException; + +import javax.jcr.PropertyType; +import javax.jcr.RepositoryException; +import javax.jcr.Session; +import javax.jcr.nodetype.NodeDefinition; +import javax.jcr.nodetype.NodeType; +import javax.jcr.nodetype.PropertyDefinition; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.core.nodetype.InvalidNodeTypeDefException; +import org.apache.jackrabbit.ocm.AbstractRepositoryTestBase; +import org.apache.jackrabbit.ocm.manager.ObjectContentManager; +import org.apache.jackrabbit.ocm.mapper.model.BeanDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.ClassDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.CollectionDescriptor; +import org.apache.jackrabbit.ocm.mapper.model.FieldDescriptor; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NamespaceCreationException; +import org.apache.jackrabbit.ocm.nodemanagement.exception.NodeTypeCreationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** JUnit test for NodeTypeManagerImpl. + * + * @author Oliver Kiessler + */ +public class NodeTypeManagerImplTest extends AbstractRepositoryTestBase { + + /** + * Logger instance. + */ + private static final Logger log = + LoggerFactory.getLogger(NodeTypeManagerImpl.class); + + /** Class to test. + */ + private NodeTypeManagerImpl nodeTypeManagerImpl + = new NodeTypeManagerImpl(); + + /** Returns testsuite. + * @return suite + */ + public static Test suite() + { + TestSuite suite = new TestSuite(NodeTypeManagerImplTest.class); + return suite; + } + + @Override + protected ObjectContentManager createObjectContentManager(Session session) throws RepositoryException { + // no ObjectContentManager needed for this test + return null; + } + + @Override + protected void registerNodeTypes(Session session) + throws InvalidNodeTypeDefException, javax.jcr.RepositoryException, IOException { + // do not register any node types at startup hence override the one from AbstractRepositoryTestBase + return; + } + + public void testCreateNamespace() throws Exception + { + + Session session = getSession(); + nodeTypeManagerImpl.createNamespace(session, + "ocmtest", "http://www.test.com/test-uri"); + + assertEquals(session.getWorkspace().getNamespaceRegistry().getPrefix("http://www.test.com/test-uri"), "ocmtest"); + assertEquals(session.getWorkspace().getNamespaceRegistry().getURI("ocmtest"), "http://www.test.com/test-uri"); + + boolean failed = false; + + try + { + nodeTypeManagerImpl.createNamespace(session, + "ocmtest", "http://www.test.com/test-uri"); + } catch (NamespaceCreationException nce) { + // expected + failed = true; + } + + assertTrue(failed); + } + + public void testCreateSingleNodeType() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.TestClass"); + classDescriptor.setJcrType("ocm:test2"); + classDescriptor.setJcrSuperTypes("nt:base"); + + FieldDescriptor field1 = new FieldDescriptor(); + field1.setFieldName("a"); + field1.setJcrName("ocm:a"); + field1.setJcrType("String"); + field1.setJcrAutoCreated(true); + field1.setJcrMandatory(true); + field1.setJcrMultiple(true); + classDescriptor.addFieldDescriptor(field1); + + FieldDescriptor field2 = new FieldDescriptor(); + field2.setFieldName("b"); + field2.setJcrName("ocm:b"); + field2.setJcrType("Long"); + field1.setJcrAutoCreated(false); + field1.setJcrMandatory(true); + field1.setJcrMultiple(false); + classDescriptor.addFieldDescriptor(field2); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType testNodeType = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test2"); + assertNotNull(testNodeType); + assertFalse(testNodeType.isMixin()); + assertEquals(testNodeType.getName(), "ocm:test2"); + assertEquals(testNodeType.getSupertypes().length, 1); + assertEquals(testNodeType.getSupertypes()[0].getName(), "nt:base"); + + // 2 defined in ocm:test2 and 2 inherited from nt:base + assertEquals(testNodeType.getPropertyDefinitions().length, 4); + + assertTrue(containsProperty("ocm:a", testNodeType.getPropertyDefinitions())); + assertTrue(containsProperty("ocm:b", testNodeType.getPropertyDefinitions())); + assertTrue(containsProperty("jcr:primaryType", testNodeType.getPropertyDefinitions())); + assertTrue(containsProperty("jcr:mixinTypes", testNodeType.getPropertyDefinitions())); + + PropertyDefinition propDef1 = getPropertyDefinition(testNodeType.getPropertyDefinitions(), "ocm:a"); + log.info(showPropertyDefinition(propDef1)); + // TODO test all properties + + PropertyDefinition propDef2 = getPropertyDefinition(testNodeType.getPropertyDefinitions(), "ocm:b"); + log.info(showPropertyDefinition(propDef2)); + // TODO test all properties + } + + public void testCreateSingleNodeTypeNoNamespace() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test3Class"); + classDescriptor.setJcrType("test3"); + classDescriptor.setJcrSuperTypes("nt:base"); + + FieldDescriptor field1 = new FieldDescriptor(); + field1.setFieldName("a"); + field1.setJcrName("a"); + field1.setJcrType("String"); + classDescriptor.addFieldDescriptor(field1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test3 = getSession().getWorkspace().getNodeTypeManager().getNodeType("test3"); + assertNotNull(test3); + assertFalse(test3.isMixin()); + assertEquals(test3.getName(), "test3"); + assertEquals(test3.getSupertypes().length, 1); + assertEquals(test3.getSupertypes()[0].getName(), "nt:base"); + } + + public void testCreateSingleNodeTypeNoJcrNodeTypeSet() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test4Class"); + classDescriptor.setJcrSuperTypes("nt:base"); + + FieldDescriptor field1 = new FieldDescriptor(); + field1.setFieldName("a"); + field1.setJcrName("a"); + field1.setJcrType("String"); + classDescriptor.addFieldDescriptor(field1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test4 = getSession().getWorkspace().getNodeTypeManager().getNodeType("test.Test4Class"); + assertNotNull(test4); + assertFalse(test4.isMixin()); + assertEquals(test4.getName(), "test.Test4Class"); + assertEquals(test4.getSupertypes().length, 1); + assertEquals(test4.getSupertypes()[0].getName(), "nt:base"); + } + + public void testCreateSingleNodeTypeIncompleteFieldDescriptorProperties() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test5Class"); + classDescriptor.setJcrType("ocm:test5"); + classDescriptor.setJcrSuperTypes("ocm:test2"); + + FieldDescriptor field1 = new FieldDescriptor(); + field1.setFieldName("abc"); + classDescriptor.addFieldDescriptor(field1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test5 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test5"); + assertNotNull(test5); + assertFalse(test5.isMixin()); + assertEquals(test5.getName(), "ocm:test5"); + // nt:base and ocm:test2 + assertEquals(test5.getSupertypes().length, 2); + assertTrue(containsSuperType("ocm:test2", test5.getSupertypes())); + assertTrue(containsSuperType("nt:base", test5.getSupertypes())); + assertTrue(containsProperty("abc", test5.getPropertyDefinitions())); + } + + public void testCreateSingleNodeTypeNtNamespace() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test6Class"); + classDescriptor.setJcrType("nt:test3"); + classDescriptor.setJcrSuperTypes("nt:base"); + + FieldDescriptor field1 = new FieldDescriptor(); + field1.setFieldName("a"); + field1.setJcrName("a"); + field1.setJcrType("String"); + classDescriptor.addFieldDescriptor(field1); + + boolean failed = false; + + try + { + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + } + catch (NodeTypeCreationException nce) + { + // excepted + failed = true; + } + + assertTrue(failed); + } + + public void testCreateSingleNodeTypeWithPropertyForCollection() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test9Class"); + classDescriptor.setJcrType("ocm:test9"); + classDescriptor.setJcrSuperTypes("nt:base"); + + CollectionDescriptor collection1 = new CollectionDescriptor(); + collection1.setFieldName("a"); + collection1.setJcrName("a"); + collection1.setJcrType("String"); + + classDescriptor.addCollectionDescriptor(collection1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test9 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test9"); + assertNotNull(test9); + // not check node type definition, assuming other tests have done that + + // assert property definition a + PropertyDefinition propDef = getPropertyDefinition(test9.getPropertyDefinitions(), "a"); + assertNotNull(propDef); + assertEquals(propDef.getRequiredType(), PropertyType.STRING); + } + + public void testCreateSingleNodeTypeWithPropertyForBean() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test10Class"); + classDescriptor.setJcrType("ocm:test10"); + classDescriptor.setJcrSuperTypes("nt:base"); + + BeanDescriptor bean1 = new BeanDescriptor(); + bean1.setFieldName("a"); + bean1.setJcrName("a"); + bean1.setJcrType("String"); + classDescriptor.addBeanDescriptor(bean1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test10 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test10"); + assertNotNull(test10); + // not check node type definition, assuming other tests have done that + + // assert property definition a + PropertyDefinition propDef = getPropertyDefinition(test10.getPropertyDefinitions(), "a"); + assertNotNull(propDef); + assertEquals(propDef.getRequiredType(), PropertyType.STRING); + + } + + public void testCreateSingleNodeTypeWithPropertyForCollectionDefinitionConflict() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test13Class"); + classDescriptor.setJcrType("ocm:test13"); + classDescriptor.setJcrSuperTypes("nt:base"); + + CollectionDescriptor collection1 = new CollectionDescriptor(); + collection1.setFieldName("a"); + collection1.setJcrName("a"); + collection1.setJcrType("String"); + classDescriptor.addCollectionDescriptor(collection1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test13 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test13"); + assertNotNull(test13); + // not check node type definition, assuming other tests have done that + + // assert property definition a + PropertyDefinition propDef = getPropertyDefinition(test13.getPropertyDefinitions(), "a"); + assertNotNull(propDef); + assertEquals(propDef.getRequiredType(), PropertyType.STRING); + } + + public void testCreateSingleNodeTypeWithPropertyForBeanDefinitionConflict() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test14Class"); + classDescriptor.setJcrType("ocm:test14"); + classDescriptor.setJcrSuperTypes("nt:base"); + + BeanDescriptor bean1 = new BeanDescriptor(); + bean1.setFieldName("a"); + bean1.setJcrName("a"); + bean1.setJcrType("String"); + classDescriptor.addBeanDescriptor(bean1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test14 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test14"); + assertNotNull(test14); + // not check node type definition, assuming other tests have done that + + // assert property definition a + PropertyDefinition propDef = getPropertyDefinition(test14.getPropertyDefinitions(), "a"); + assertNotNull(propDef); + assertEquals(propDef.getRequiredType(), PropertyType.STRING); + + } + + public void testCreateSingleNodeTypeWithChildNodeForCollection() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test11Class"); + classDescriptor.setJcrType("ocm:test11"); + classDescriptor.setJcrSuperTypes("nt:base"); + + CollectionDescriptor collection1 = new CollectionDescriptor(); + collection1.setFieldName("a"); + collection1.setJcrName("b"); + collection1.setJcrType("nt:unstructured"); + classDescriptor.addCollectionDescriptor(collection1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test11 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test11"); + assertNotNull(test11); + // not check node type definition, assuming other tests have done that + + // assert child node definition a + NodeDefinition nodeDef = getChildNodeDefinition(test11.getChildNodeDefinitions(), "b"); + assertNotNull(nodeDef); + assertNotNull(nodeDef.getRequiredPrimaryTypes()); + assertEquals(nodeDef.getRequiredPrimaryTypes().length, 1); + assertEquals(nodeDef.getRequiredPrimaryTypes()[0].getName(), "nt:unstructured"); + } + + public void testCreateSingleNodeTypeWithChildNodeForBean() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test12Class"); + classDescriptor.setJcrType("ocm:test12"); + classDescriptor.setJcrSuperTypes("nt:base"); + + BeanDescriptor bean1 = new BeanDescriptor(); + bean1.setFieldName("a"); + bean1.setJcrName("b"); + bean1.setJcrType("nt:unstructured"); + classDescriptor.addBeanDescriptor(bean1); + + nodeTypeManagerImpl.createSingleNodeType(getSession(), classDescriptor); + + NodeType test12 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test12"); + assertNotNull(test12); + // not check node type definition, assuming other tests have done that + + // assert property definition a + NodeDefinition nodeDef = getChildNodeDefinition(test12.getChildNodeDefinitions(), "b"); + assertNotNull(nodeDef); + assertNotNull(nodeDef.getRequiredPrimaryTypes()); + assertEquals(nodeDef.getRequiredPrimaryTypes().length, 1); + assertEquals(nodeDef.getRequiredPrimaryTypes()[0].getName(), "nt:unstructured"); + } + + public void testCreateNodeTypes() throws Exception + { + ClassDescriptor classDescriptor = new ClassDescriptor(); + classDescriptor.setClassName("test.Test6Class"); + classDescriptor.setJcrType("ocm:test6"); + classDescriptor.setJcrSuperTypes("nt:base"); + + FieldDescriptor field1 = new FieldDescriptor(); + field1.setFieldName("a"); + field1.setJcrName("ocm:a"); + field1.setJcrType("String"); + classDescriptor.addFieldDescriptor(field1); + + FieldDescriptor field2 = new FieldDescriptor(); + field2.setFieldName("b"); + field2.setJcrName("ocm:b"); + field2.setJcrType("Long"); + classDescriptor.addFieldDescriptor(field2); + + ClassDescriptor classDescriptor2 = new ClassDescriptor(); + classDescriptor2.setClassName("test.Test7Class"); + classDescriptor2.setJcrType("ocm:test7"); + classDescriptor2.setJcrSuperTypes("nt:base"); + + FieldDescriptor field3 = new FieldDescriptor(); + field3.setFieldName("a"); + field3.setJcrName("ocm:a"); + field3.setJcrType("String"); + classDescriptor2.addFieldDescriptor(field3); + + FieldDescriptor field4 = new FieldDescriptor(); + field4.setFieldName("b"); + field4.setJcrName("ocm:b"); + field4.setJcrType("Long"); + classDescriptor2.addFieldDescriptor(field4); + + ClassDescriptor[] classDescriptorArray = new ClassDescriptor[2]; + classDescriptorArray[0] = classDescriptor; + classDescriptorArray[1] = classDescriptor2; + + nodeTypeManagerImpl.createNodeTypes(getSession(), classDescriptorArray); + + NodeType test6 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test6"); + assertNotNull(test6); + + NodeType test7 = getSession().getWorkspace().getNodeTypeManager().getNodeType("ocm:test7"); + assertNotNull(test7); + } + + /** Returns true if a given property is found in an array of property + * definitions. + * + * @param propertyName Name of property to find + * @param propDefs Properties of a node type + * @return true/false + */ + protected boolean containsProperty(String propertyName, + PropertyDefinition[] propDefs) + { + boolean found = false; + + for (int i = 0; i < propDefs.length; i++) + { + if (propDefs[i].getName().equals(propertyName)) + { + found = true; + break; + } + } + + return found; + } + + /** Returns a property defintion identified by its name. + * + * @param propDefs All property definitions of a node type + * @param propertyName Name of property definition + * @return found + */ + protected PropertyDefinition getPropertyDefinition(PropertyDefinition[] propDefs, + String propertyName) + { + PropertyDefinition found = null; + + for (int i = 0; i < propDefs.length; i++) + { + if (propDefs[i].getName().equals(propertyName)) + { + found = propDefs[i]; + break; + } + } + + return found; + } + + /** Returns true if a given child node is found in an array of child node + * definitions. + * + * @param childNodeName Name of child node to find + * @param childNodeDefs Child nodes of a node type + * @return true/false + */ + protected boolean containsChildNode(String childNodeName, + NodeDefinition[] childNodeDefs) + { + boolean found = false; + + for (int i = 0; i < childNodeDefs.length; i++) + { + if (childNodeDefs[i].getName().equals(childNodeName)) + { + found = true; + break; + } + } + + return found; + } + + /** Returns a property defintion identified by its name. + * + * @param childNodeDefs Child nodes of a node type + * @param childNodeName Name of child node to find + * @return found + */ + protected NodeDefinition getChildNodeDefinition(NodeDefinition[] childNodeDefs, + String childNodeName) + { + NodeDefinition found = null; + + for (int i = 0; i < childNodeDefs.length; i++) + { + if (childNodeDefs[i].getName().equals(childNodeName)) + { + found = childNodeDefs[i]; + break; + } + } + + return found; + } + + /** Returns true if a given super type is found in an arry of super types. + * + * @param superType Name of super type to find + * @param nodeTypes + * @return true/false + */ + protected boolean containsSuperType(String superType, + NodeType[] nodeTypes) + { + boolean found = false; + + for (int i = 0; i < nodeTypes.length; i++) + { + if (nodeTypes[i].getName().equals(superType)) + { + found = true; + break; + } + } + + return found; + } + + /** Returns true if a property was found in an array of property defintions. + * + * @param definitions PropertyDefinition[] + * @param propertyName Name of property to find + * @return true/false + */ + public boolean containsPropertyDefintion(PropertyDefinition[] definitions, + String propertyName) + { + boolean found = false; + + if (definitions != null && definitions.length > 0) + { + for (int i = 0; i < definitions.length; i++) + { + if (definitions[i].getName().equals(propertyName)) + { + found = true; + } + } + } + + return found; + } + + + /** + * + * @param propDef + * @return + */ + protected String showPropertyDefinition(PropertyDefinition propDef) + { + StringBuffer sb = new StringBuffer(); + sb.append("----"); + sb.append("\nName: " + propDef.getName()); + sb.append("\nAutocreated: " + propDef.isAutoCreated()); + sb.append("\nMandatory: " + propDef.isMandatory()); + sb.append("\n----"); + return sb.toString(); + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/querymanager/AllTests.java b/src/test/java/org/apache/jackrabbit/ocm/querymanager/AllTests.java new file mode 100644 index 00000000..bcac1411 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/querymanager/AllTests.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.querymanager; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +/** + * Package level tests. + * + * @author Alexandru Popescu + */ +public class AllTests { + + public static Test suite() { + return buildSuite(); + } + + public static Test buildSuite() { + TestSuite suite= new TestSuite("Test for org.apache.jackrabbit.ocm.querymanager"); + //$JUnit-BEGIN$ + suite.addTestSuite(AnnotationQueryManagerTest.class); + suite.addTestSuite(DigesterQueryManagerTest.class); + + + //$JUnit-END$ + + return suite; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/querymanager/AnnotationQueryManagerTest.java b/src/test/java/org/apache/jackrabbit/ocm/querymanager/AnnotationQueryManagerTest.java new file mode 100644 index 00000000..d557c244 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/querymanager/AnnotationQueryManagerTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.querymanager; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.AnnotationRepositoryTestBase; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.C; + + +/** + * Test QueryManagerImpl methods + * + * @author Christophe Lombart + */ +public class AnnotationQueryManagerTest extends AnnotationRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(AnnotationQueryManagerTest.class); + } + + public void testBuildExpression1() + { + try + { + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(C.class); + filter.addEqualTo("name", "a test value") + .addEqualTo("id", new Integer(1)); + filter.setScope("/test//"); + + Query query = queryManager.createQuery(filter); + String jcrExpression = queryManager.buildJCRExpression(query); + assertNotNull("jcrExpression is null", jcrExpression); + assertTrue("Invalid JcrExpression", jcrExpression.equals("/jcr:root/test//element(*, ocm:C) [@ocm:name = 'a test value' and @ocm:id = 1]")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + public void testBuildExpression2() + { + + try + { + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(C.class); + filter.addEqualTo("name", "a test value") + .addEqualTo("id", new Integer(1)); + + Query query = queryManager.createQuery(filter); + String jcrExpression = queryManager.buildJCRExpression(query); + assertNotNull("jcrExpression is null", jcrExpression); + assertTrue("Invalid JcrExpression", jcrExpression.equals("//element(*, ocm:C) [@ocm:name = 'a test value' and @ocm:id = 1]")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/querymanager/DigesterQueryManagerTest.java b/src/test/java/org/apache/jackrabbit/ocm/querymanager/DigesterQueryManagerTest.java new file mode 100644 index 00000000..98160e77 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/querymanager/DigesterQueryManagerTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.querymanager; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jackrabbit.ocm.DigesterRepositoryTestBase; +import org.apache.jackrabbit.ocm.query.Filter; +import org.apache.jackrabbit.ocm.query.Query; +import org.apache.jackrabbit.ocm.query.QueryManager; +import org.apache.jackrabbit.ocm.testmodel.C; + + +/** + * Test QueryManagerImpl methods + * + * @author Christophe Lombart + */ +public class DigesterQueryManagerTest extends DigesterRepositoryTestBase +{ + + public static Test suite() + { + // All methods starting with "test" will be executed in the test suite. + return new TestSuite(DigesterQueryManagerTest.class); + } + + public void testBuildExpression1() + { + try + { + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(C.class); + filter.addEqualTo("name", "a test value") + .addEqualTo("id", new Integer(1)); + filter.setScope("/test//"); + + Query query = queryManager.createQuery(filter); + String jcrExpression = queryManager.buildJCRExpression(query); + assertNotNull("jcrExpression is null", jcrExpression); + assertTrue("Invalid JcrExpression", jcrExpression.equals("/jcr:root/test//element(*, ocm:C) [@ocm:name = 'a test value' and @ocm:id = 1]")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + public void testBuildExpression2() + { + + try + { + QueryManager queryManager = getObjectContentManager().getQueryManager(); + Filter filter = queryManager.createFilter(C.class); + filter.addEqualTo("name", "a test value") + .addEqualTo("id", new Integer(1)); + + Query query = queryManager.createQuery(filter); + String jcrExpression = queryManager.buildJCRExpression(query); + assertNotNull("jcrExpression is null", jcrExpression); + assertTrue("Invalid JcrExpression", jcrExpression.equals("//element(*, ocm:C) [@ocm:name = 'a test value' and @ocm:id = 1]")); + } + catch (Exception e) + { + e.printStackTrace(); + fail("Exception occurs during the unit test : " + e); + } + + } + + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/reflection/ReflectionUtilsTest.java b/src/test/java/org/apache/jackrabbit/ocm/reflection/ReflectionUtilsTest.java new file mode 100644 index 00000000..a149572e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/reflection/ReflectionUtilsTest.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.reflection; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.TestCase; + +public class ReflectionUtilsTest extends TestCase { + + public void testImplementsInterface() { + assertTrue(ReflectionUtils + .implementsInterface(HashMap.class, Map.class)); + assertTrue(ReflectionUtils.implementsInterface( + Collections.EMPTY_MAP.getClass(), Map.class)); + } + +} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/A.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/A.java similarity index 56% rename from src/test/org/apache/portals/graffito/jcr/testmodel/A.java rename to src/test/java/org/apache/jackrabbit/ocm/testmodel/A.java index 673e5008..eba6fa08 100644 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/A.java +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/A.java @@ -1,131 +1,137 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class A -{ - private String path; - private String a1; - private String a2; - private B b; - private B emptyB; - private Collection collection; - private Collection emptyCollection; - - - - public String getPath() { - return path; - } - public void setPath(String path) { - this.path = path; - } - /** - * @return Returns the a1. - */ - public String getA1() - { - return a1; - } - /** - * @param a1 The a1 to set. - */ - public void setA1(String a1) - { - this.a1 = a1; - } - /** - * @return Returns the a2. - */ - public String getA2() - { - return a2; - } - /** - * @param a2 The a2 to set. - */ - public void setA2(String a2) - { - this.a2 = a2; - } - /** - * @return Returns the b. - */ - public B getB() - { - return b; - } - /** - * @param b The b to set. - */ - public void setB(B b) - { - this.b = b; - } - - - /** - * @return Returns the collection. - */ - public Collection getCollection() - { - return collection; - } - - /** - * @param collection The collection to set. - */ - public void setCollection(Collection collection) - { - this.collection = collection; - } - - public void addC(C c) - { - if (collection == null ) - { - collection = new ArrayList(); - } - - collection.add(c); - } - public Collection getEmptyCollection() - { - return emptyCollection; - } - public void setEmptyCollection(Collection emptyCollection) - { - this.emptyCollection = emptyCollection; - } - public B getEmptyB() - { - return emptyB; - } - public void setEmptyB(B emptyB) - { - this.emptyB = emptyB; - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.util.ArrayList; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(jcrMixinTypes="mix:lockable" ) +public class A +{ + @Field(path=true) private String path; + @Field private String a1; + @Field private String a2; + @Bean(jcrType="nt:unstructured", jcrOnParentVersion="IGNORE") private B b; + + private B emptyB; + + @Collection(elementClassName=C.class, jcrType="nt:unstructured", jcrOnParentVersion="IGNORE") private java.util.Collection collection; + @Collection(elementClassName=C.class) private java.util.Collection emptyCollection; + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + /** + * @return Returns the a1. + */ + public String getA1() + { + return a1; + } + /** + * @param a1 The a1 to set. + */ + public void setA1(String a1) + { + this.a1 = a1; + } + /** + * @return Returns the a2. + */ + public String getA2() + { + return a2; + } + /** + * @param a2 The a2 to set. + */ + public void setA2(String a2) + { + this.a2 = a2; + } + /** + * @return Returns the b. + */ + public B getB() + { + return b; + } + /** + * @param b The b to set. + */ + public void setB(B b) + { + this.b = b; + } + + + /** + * @return Returns the collection. + */ + public java.util.Collection getCollection() + { + return collection; + } + + /** + * @param collection The collection to set. + */ + public void setCollection(java.util.Collection collection) + { + this.collection = collection; + } + + public void addC(C c) + { + if (collection == null ) + { + collection = new ArrayList(); + } + + collection.add(c); + } + public java.util.Collection getEmptyCollection() + { + return emptyCollection; + } + public void setEmptyCollection(java.util.Collection emptyCollection) + { + this.emptyCollection = emptyCollection; + } + public B getEmptyB() + { + return emptyB; + } + public void setEmptyB(B emptyB) + { + this.emptyB = emptyB; + } + + +} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/Atomic.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Atomic.java similarity index 53% rename from src/test/org/apache/portals/graffito/jcr/testmodel/Atomic.java rename to src/test/java/org/apache/jackrabbit/ocm/testmodel/Atomic.java index e759deb2..2576461f 100644 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/Atomic.java +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Atomic.java @@ -1,163 +1,249 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -import java.io.InputStream; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; - -/** - * - * Simple object used to test atomic type - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class Atomic -{ - private String path; - private String string; - private Boolean booleanObject; - private boolean booleanPrimitive; - private Integer integerObject; - private int intPrimitive; - private byte[] byteArray; - private Calendar calendar; - private Date date; - private Double doubleObject; - private double doublePrimitive; - private InputStream inputStream; - private Timestamp timestamp; - private Collection multiValue; - - - - public String getPath() { - return path; - } - public void setPath(String path) { - this.path = path; - } - public Boolean getBooleanObject() - { - return booleanObject; - } - public void setBooleanObject(Boolean booleanObject) - { - this.booleanObject = booleanObject; - } - public boolean isBooleanPrimitive() - { - return booleanPrimitive; - } - public void setBooleanPrimitive(boolean booleanPrimitive) - { - this.booleanPrimitive = booleanPrimitive; - } - public Integer getIntegerObject() - { - return integerObject; - } - public void setIntegerObject(Integer integerObject) - { - this.integerObject = integerObject; - } - public int getIntPrimitive() - { - return intPrimitive; - } - public void setIntPrimitive(int intPrimitive) - { - this.intPrimitive = intPrimitive; - } - public String getString() - { - return string; - } - public void setString(String string) - { - this.string = string; - } - public byte[] getByteArray() - { - return byteArray; - } - public void setByteArray(byte[] byteArray) - { - this.byteArray = byteArray; - } - public Calendar getCalendar() - { - return calendar; - } - public void setCalendar(Calendar calandar) - { - this.calendar = calandar; - } - public Date getDate() - { - return date; - } - public void setDate(Date date) - { - this.date = date; - } - public Double getDoubleObject() - { - return doubleObject; - } - public void setDoubleObject(Double doubleObject) - { - this.doubleObject = doubleObject; - } - public double getDoublePrimitive() - { - return doublePrimitive; - } - public void setDoublePrimitive(double doublePrimitive) - { - this.doublePrimitive = doublePrimitive; - } - public InputStream getInputStream() - { - return inputStream; - } - public void setInputStream(InputStream inputStream) - { - this.inputStream = inputStream; - } - public Timestamp getTimestamp() - { - return timestamp; - } - public void setTimestamp(Timestamp timestamp) - { - this.timestamp = timestamp; - } - - public Collection getMultiValue() - { - return multiValue; - } - public void setMultiValue(Collection multiValue) - { - this.multiValue = multiValue; - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.io.InputStream; +import java.sql.Timestamp; +import java.util.Calendar; +import java.util.Date; + +import org.apache.jackrabbit.ocm.manager.atomic.Int2BooleanTypeConverterImpl; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.NameTypeConverterImpl; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.PathTypeConverterImpl; +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.UndefinedTypeConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * Simple object used to test atomic type + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node +public class Atomic +{ + @Field(path=true) protected String path; + @Field private String string; + @Field private Boolean booleanObject; + @Field private boolean booleanPrimitive; + @Field private Integer integerObject; + @Field private int intPrimitive; + @Field private byte[] byteArray; + @Field private Calendar calendar; + @Field private Date date; + @Field private Double doubleObject; + @Field private double doublePrimitive; + @Field private InputStream inputStream; + @Field private Timestamp timestamp; + + @Field (converter = Int2BooleanTypeConverterImpl.class) + private boolean int2boolean; + + @Field (converter = NameTypeConverterImpl.class) + private String namedProperty; + + @Field (converter = PathTypeConverterImpl.class) + private String pathProperty; // used to refer another node + + @Field (converter = UndefinedTypeConverterImpl.class) + private Object undefinedProperty; + + + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + + + public Boolean getBooleanObject() + { + return booleanObject; + } + + public void setBooleanObject(Boolean booleanObject) + { + this.booleanObject = booleanObject; + } + + + public boolean isBooleanPrimitive() + { + return booleanPrimitive; + } + + public void setBooleanPrimitive(boolean booleanPrimitive) + { + this.booleanPrimitive = booleanPrimitive; + } + + + public Integer getIntegerObject() + { + return integerObject; + + } + public void setIntegerObject(Integer integerObject) + { + this.integerObject = integerObject; + } + + + public int getIntPrimitive() + { + return intPrimitive; + } + + public void setIntPrimitive(int intPrimitive) + { + this.intPrimitive = intPrimitive; + } + + + public String getString() + { + return string; + } + public void setString(String string) + { + this.string = string; + } + + + public byte[] getByteArray() + { + return byteArray; + } + + public void setByteArray(byte[] byteArray) + { + this.byteArray = byteArray; + } + + + public Calendar getCalendar() + { + return calendar; + } + + + public void setCalendar(Calendar calandar) + { + this.calendar = calandar; + } + + + public Date getDate() + { + return date; + } + + public void setDate(Date date) + { + this.date = date; + } + + + public Double getDoubleObject() + { + return doubleObject; + } + + public void setDoubleObject(Double doubleObject) + { + this.doubleObject = doubleObject; + } + + + public double getDoublePrimitive() + { + return doublePrimitive; + } + + public void setDoublePrimitive(double doublePrimitive) + { + this.doublePrimitive = doublePrimitive; + } + + + public InputStream getInputStream() + { + return inputStream; + } + public void setInputStream(InputStream inputStream) + { + this.inputStream = inputStream; + } + + + public Timestamp getTimestamp() + { + return timestamp; + } + + public void setTimestamp(Timestamp timestamp) + { + this.timestamp = timestamp; + } + + public boolean isInt2boolean() + { + return int2boolean; + } + + public void setInt2boolean(boolean int2boolean) + { + this.int2boolean = int2boolean; + } + + + public String getNamedProperty() { + return namedProperty; + } + + + public void setNamedProperty(String namedProperty) + { + this.namedProperty = namedProperty; + } + + public String getPathProperty() + { + return pathProperty; + } + + public void setPathProperty(String pathProperty) + { + this.pathProperty = pathProperty; + } + + + public Object getUndefinedProperty() + { + return undefinedProperty; + } + + public void setUndefinedProperty(Object undefinedProperty) + { + this.undefinedProperty = undefinedProperty; + } + + +} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/B.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/B.java similarity index 51% rename from src/test/org/apache/portals/graffito/jcr/testmodel/B.java rename to src/test/java/org/apache/jackrabbit/ocm/testmodel/B.java index 663f5406..c014b63a 100644 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/B.java +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/B.java @@ -1,57 +1,71 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -/** - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class B -{ - private String b1; - private String b2; - - - /** - * @return Returns the b1. - */ - public String getB1() - { - return b1; - } - /** - * @param b1 The b1 to set. - */ - public void setB1(String b1) - { - this.b1 = b1; - } - /** - * @return Returns the b2. - */ - public String getB2() - { - return b2; - } - /** - * @param b2 The b2 to set. - */ - public void setB2(String b2) - { - this.b2 = b2; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(jcrType="nt:unstructured", jcrSuperTypes="nt:base") +public class B +{ + @Field(jcrType="String", jcrOnParentVersion="IGNORE") private String b1; + @Field(jcrType="String", jcrOnParentVersion="IGNORE") private String b2; + private A a; + + + /** + * @return Returns the b1. + */ + public String getB1() + { + return b1; + } + /** + * @param b1 The b1 to set. + */ + public void setB1(String b1) + { + this.b1 = b1; + } + /** + * @return Returns the b2. + */ + public String getB2() + { + return b2; + } + /** + * @param b2 The b2 to set. + */ + public void setB2(String b2) + { + this.b2 = b2; + } + public A getA() { + return a; + } + public void setA(A a) { + this.a = a; + } + + +} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/C.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/C.java similarity index 56% rename from src/test/org/apache/portals/graffito/jcr/testmodel/C.java rename to src/test/java/org/apache/jackrabbit/ocm/testmodel/C.java index 7754a75c..ebd74112 100644 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/C.java +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/C.java @@ -1,56 +1,62 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -/** - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class C -{ - private String id; - private String name; - - /** - * @return Returns the id. - */ - public String getId() - { - return id; - } - /** - * @param id The id to set. - */ - public void setId(String id) - { - this.id = id; - } - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } - /** - * @param name The name to set. - */ - public void setName(String name) - { - this.name = name; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(jcrType="ocm:C", discriminator=false) +public class C +{ + + @Field(jcrName="ocm:id", id=true) private String id; + @Field(jcrName="ocm:name") private String name; + + /** + * @return Returns the id. + */ + public String getId() + { + return id; + } + /** + * @param id The id to set. + */ + public void setId(String id) + { + this.id = id; + } + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + /** + * @param name The name to set. + */ + public void setName(String name) + { + this.name = name; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/D.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/D.java new file mode 100644 index 00000000..7df0c23b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/D.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.InlineBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * @author Alexandru Popescu + */ +@Node +public class D { + @Field(path=true) private String path; + @Field private String d1; + @Bean(converter=InlineBeanConverterImpl.class)private B b1; + + /** + * @return Returns the dB. + */ + public B getB1() { + return this.b1; + } + + /** + * @param db The dB to set. + */ + public void setB1(B db) { + this.b1 = db; + } + + /** + * @return Returns the dString. + */ + public String getD1() { + return this.d1; + } + + /** + * @param string The dString to set. + */ + public void setD1(String string) { + this.d1 = string; + } + + /** + * @return Returns the path. + */ + public String getPath() { + return path; + } + + /** + * @param path The path to set. + */ + public void setPath(String path) { + this.path= path; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/DFull.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/DFull.java new file mode 100644 index 00000000..a2339552 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/DFull.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * @author Alexandru Popescu + */ +@Node +public class DFull { + @Field(path=true) private String path; + @Field private String d1; + @Field private String b1; + @Field private String b2; + + /** + * @return Returns the b1. + */ + public String getB1() { + return b1; + } + + /** + * @param b1 The b1 to set. + */ + public void setB1(String b1) { + this.b1 = b1; + } + + /** + * @return Returns the b2. + */ + public String getB2() { + return b2; + } + + /** + * @param b2 The b2 to set. + */ + public void setB2(String b2) { + this.b2 = b2; + } + + /** + * @return Returns the dString. + */ + public String getD1() { + return this.d1; + } + + /** + * @param string The dString to set. + */ + public void setD1(String string) { + this.d1 = string; + } + + /** + * @return Returns the path. + */ + public String getPath() { + return path; + } + + /** + * @param path The path to set. + */ + public void setPath(String path) { + this.path= path; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Default.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Default.java new file mode 100644 index 00000000..89cb3e9a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Default.java @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * Simple object used to test default value assignement + */ +@Node(jcrType="ocm:DefTestPrimary", discriminator=false) +public class Default +{ + @Field(path=true) private String path; + + @Field(jcrName="ocm:p1") private String p1; + + @Field(jcrName="ocm:p2") private String p2; + + @Field(jcrName="ocm:p3", jcrDefaultValue="p3DescriptorDefaultValue") + private String p3; + + @Field(jcrName="ocm:p4") private String p4; + + @Field(jcrName="ocm:p5") private String p5; + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + /** + * @return the p1 + */ + public String getP1() { + return p1; + } + + /** + * @param p1 the p1 to set + */ + public void setP1(String p1) { + this.p1 = p1; + } + + /** + * @return the p2 + */ + public String getP2() { + return p2; + } + + /** + * @param p2 the p2 to set + */ + public void setP2(String p2) { + this.p2 = p2; + } + + /** + * @return the p3 + */ + public String getP3() { + return p3; + } + + /** + * @param p3 the p3 to set + */ + public void setP3(String p3) { + this.p3 = p3; + } + + /** + * @return the p4 + */ + public String getP4() { + return p4; + } + + /** + * @param p4 the p4 to set + */ + public void setP4(String p4) { + this.p4 = p4; + } + + /** + * @return the p5 + */ + public String getP5() { + return p5; + } + + /** + * @param p5 the p5 to set + */ + public void setP5(String p5) { + this.p5 = p5; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Discriminator.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Discriminator.java new file mode 100644 index 00000000..8ab17232 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Discriminator.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * @author Christophe Lombart + */ +@Node +public class Discriminator { + @Field(path=true) private String path; + @Field private String content; + + public String getContent() { + return content; + } + public void setContent(String content) { + this.content = content; + } + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/E.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/E.java new file mode 100644 index 00000000..09957d9c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/E.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.manager.beanconverter.FakeBeanConverter; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * @author Alexandru Popescu + */ +@Node +public class E +{ + @Field(path=true) private String path; + @Field private String d1; + @Bean(converter=FakeBeanConverter.class)private B b1; + + /** + * @return Returns the dB. + */ + public B getB1() { + return this.b1; + } + + /** + * @param db The dB to set. + */ + public void setB1(B db) { + this.b1 = db; + } + + /** + * @return Returns the dString. + */ + public String getD1() { + return this.d1; + } + + /** + * @param string The dString to set. + */ + public void setD1(String string) { + this.d1 = string; + } + + /** + * @return Returns the path. + */ + public String getPath() { + return path; + } + + /** + * @param path The path to set. + */ + public void setPath(String path) { + this.path= path; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/File.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/File.java new file mode 100755 index 00000000..c740ce24 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/File.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * Java class used to map the jcr node type nt:file + * @author Lombart Christophe + * + */ +@Node(jcrType="nt:file", extend=HierarchyNode.class) +public class File extends HierarchyNode +{ + + @Bean(jcrName="jcr:content") private Resource resource; + + public Resource getResource() + { + return resource; + } + + public void setResource(Resource resource) + { + this.resource = resource; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Folder.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Folder.java new file mode 100644 index 00000000..e75cbead --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Folder.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.util.ArrayList; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.NTCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +/** + * Java class used to map the jcr node type nt:folder + * @author Lombart Christophe + * + */ +@Node(jcrType="nt:folder", extend=HierarchyNode.class ) +public class Folder extends HierarchyNode +{ + @Collection(autoUpdate=false, elementClassName=HierarchyNode.class , collectionConverter=NTCollectionConverterImpl.class) + private java.util.Collection children; + + + public java.util.Collection getChildren() + { + return children; + } + + public void setChildren(java.util.Collection children) + { + this.children = children; + } + + public void addChild(HierarchyNode node) + { + if (children == null) + { + children = new ArrayList(); + } + children.add(node); + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/HierarchyNode.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/HierarchyNode.java new file mode 100644 index 00000000..5d94478c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/HierarchyNode.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.util.Calendar; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * Java class used to map the jcr node type nt:hierarchyNode + * @author Lombart Christophe + * + */ +@Node(jcrType="nt:hierarchyNode") +public class HierarchyNode +{ + @Field(path=true) private String path; + @Field(jcrName="jcr:created") private Calendar creationDate; + + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public Calendar getCreationDate() + { + return creationDate; + } + + public void setCreationDate(Calendar creationDate) + { + this.creationDate = creationDate; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Lockable.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Lockable.java new file mode 100644 index 00000000..c0ea43a2 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Lockable.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * + */ +@Node(jcrType="ocm:TestLockable") +public class Lockable +{ + @Field(path=true) private String path; + @Field(jcrName="ocm:a1") private String a1; + @Field(jcrName="ocm:a2") private String a2; + @Field(jcrName="jcr:lockOwner") private String lockOwner; + + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + /** + * @return Returns the a1. + */ + public String getA1() + { + return a1; + } + /** + * @param a1 The a1 to set. + */ + public void setA1(String a1) + { + this.a1 = a1; + } + /** + * @return Returns the a2. + */ + public String getA2() + { + return a2; + } + /** + * @param a2 The a2 to set. + */ + public void setA2(String a2) + { + this.a2 = a2; + } + + public String getLockOwner() + { + return lockOwner; + } + + public void setLockOwner(String lockOwner) + { + this.lockOwner = lockOwner; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/MultiValue.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/MultiValue.java new file mode 100644 index 00000000..bbb24202 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/MultiValue.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + + + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.MultiValueCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * Simple object used to test multivalue properties + * + * @author Lombart + * Christophe + * @version $Id: Exp $ + */ +@Node +public class MultiValue +{ + @Field(path=true) private String path; + + @Field private String name; + + @Collection(elementClassName=String.class, collectionConverter=MultiValueCollectionConverterImpl.class) + private java.util.Collection multiValues; + + @Collection(elementClassName=String.class, collectionConverter=MultiValueCollectionConverterImpl.class) + private java.util.Collection nullMultiValues; + + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param name The name to set. + */ + public void setName(String name) + { + this.name = name; + } + + /** + * @return Returns the multiValues. + */ + public java.util.Collection getMultiValues() + { + return multiValues; + } + + /** + * @param multiValues + * The multiValues to set. + */ + public void setMultiValues(java.util.Collection multiValues) + { + this.multiValues = multiValues; + } + + /** + * @return Returns the nullMultiValues. + */ + public java.util.Collection getNullMultiValues() + { + return nullMultiValues; + } + + /** + * @param nullMultiValues + * The nullMultiValues to set. + */ + public void setNullMultiValues(java.util.Collection nullMultiValues) + { + this.nullMultiValues = nullMultiValues; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/MultiValueWithObjectCollection.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/MultiValueWithObjectCollection.java new file mode 100644 index 00000000..11cb5ab2 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/MultiValueWithObjectCollection.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.MultiValueCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +@Node +public class MultiValueWithObjectCollection { + /** + * + * Simple object used to test multivalue properties + * + * @author Boni Gopalan + * @version $Id: Exp $ + */ + @Field(path=true) private String path; + + @Field private String name; + + @Collection(elementClassName=Object.class, collectionConverter=MultiValueCollectionConverterImpl.class) + private java.util.Collection multiValues; + + @Collection(elementClassName=Object.class, collectionConverter=MultiValueCollectionConverterImpl.class) + private java.util.Collection nullMultiValues; + + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param name The name to set. + */ + public void setName(String name) + { + this.name = name; + } + + /** + * @return Returns the multiValues. + */ + public java.util.Collection getMultiValues() + { + return multiValues; + } + + /** + * @param multiValues + * The multiValues to set. + */ + public void setMultiValues(java.util.Collection multiValues) + { + this.multiValues = multiValues; + } + + /** + * @return Returns the nullMultiValues. + */ + public java.util.Collection getNullMultiValues() + { + return nullMultiValues; + } + + /** + * @param nullMultiValues + * The nullMultiValues to set. + */ + public void setNullMultiValues(java.util.Collection nullMultiValues) + { + this.nullMultiValues = nullMultiValues; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/OcmTestProperty.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/OcmTestProperty.java new file mode 100644 index 00000000..aa7685d3 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/OcmTestProperty.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * + */ +@Node(jcrType="ocm:ocmtestproperty") +public class OcmTestProperty +{ + @Field(path=true) private String path; + @Field(jcrName="ocm:requiredProp") private String requiredProp; + @Field(jcrName="ocm:requiredWithConstraintsProp", jcrValueConstraints="abc,def,ghi") private String requiredWithConstraintsProp; + @Field(jcrName="ocm:autoCreatedProp", jcrDefaultValue="aaa") private String autoCreatedProp; + @Field(jcrName="ocm:autoCreatedWithConstraintsProp", jcrDefaultValue="ccc", jcrValueConstraints="bbb,ccc,ddd") private String autoCreatedWithConstraintsProp; + @Field(jcrName="ocm:mandatoryProp", jcrMandatory=true) private String mandatoryProp; + @Field(jcrName="ocm:mandatoryWithConstaintsProp", jcrMandatory=true, jcrValueConstraints="xx,yy") private String mandatoryWithConstaintsProp; + @Field(jcrName="ocm:protectedWithDefaultValueProp", jcrProtected=true) private String protectedWithDefaultValueProp; + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + public String getAutoCreatedProp() { + return autoCreatedProp; + } + public void setAutoCreatedProp(String autoCreadetProp) { + this.autoCreatedProp = autoCreadetProp; + } + public String getAutoCreatedWithConstraintsProp() { + return autoCreatedWithConstraintsProp; + } + public void setAutoCreatedWithConstraintsProp( + String autoCreatedWithConstraintsProp) { + this.autoCreatedWithConstraintsProp = autoCreatedWithConstraintsProp; + } + public String getMandatoryProp() { + return mandatoryProp; + } + public void setMandatoryProp(String mandatoryProp) { + this.mandatoryProp = mandatoryProp; + } + public String getMandatoryWithConstaintsProp() { + return mandatoryWithConstaintsProp; + } + public void setMandatoryWithConstaintsProp(String mandatoryWithConstaintsProp) { + this.mandatoryWithConstaintsProp = mandatoryWithConstaintsProp; + } + public String getProtectedWithDefaultValueProp() { + return protectedWithDefaultValueProp; + } + public void setProtectedWithDefaultValueProp( + String protectedWithDefaultValueProp) { + this.protectedWithDefaultValueProp = protectedWithDefaultValueProp; + } + public String getRequiredProp() { + return requiredProp; + } + public void setRequiredProp(String requiredProp) { + this.requiredProp = requiredProp; + } + public String getRequiredWithConstraintsProp() { + return requiredWithConstraintsProp; + } + public void setRequiredWithConstraintsProp(String requiredWithConstraintsProp) { + this.requiredWithConstraintsProp = requiredWithConstraintsProp; + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Page.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Page.java new file mode 100755 index 00000000..b7b8cf64 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Page.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.NTCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:page", discriminator=false) +public class Page +{ + @Field(path=true) String path; + @Field(jcrName="ocm:title") String title; + + @Collection(collectionConverter=NTCollectionConverterImpl.class, jcrElementName="paragraph") + List paragraphs; + + public String getPath() + { + return path; + } + public void setPath(String path) + { + this.path = path; + } + /** + * @return Returns the paragraphs. + */ + public List getParagraphs() + { + return paragraphs; + } + /** + * @param paragraphs The paragraphs to set. + */ + public void setParagraphs(List paragraphs) + { + this.paragraphs = paragraphs; + } + /** + * @return Returns the title. + */ + public String getTitle() + { + return title; + } + /** + * @param title The title to set. + */ + public void setTitle(String title) + { + this.title = title; + } + + public void addParagraph(Paragraph paragraph) + { + if (paragraphs == null) + { + paragraphs = new ArrayList(); + } + + paragraphs.add(paragraph); + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Paragraph.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Paragraph.java new file mode 100755 index 00000000..f989924d --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Paragraph.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ParentBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:paragraph", discriminator=false) +public class Paragraph +{ + @Field(path=true) private String path; + @Field(jcrName="ocm:text") private String text; + + // The converter ParentBeanConverterImpl can be used to have a simple reference + // to the page containing this pararaph (parent node) - cannot be updated + @Bean(proxy=true, converter=ParentBeanConverterImpl.class) private Page page; + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public Paragraph() + { + this.text = "Default text"; + } + + public Paragraph(String text) + { + this.text = text; + } + + /** + * @return Returns the text. + */ + public String getText() + { + return text; + } + + /** + * @param text The text to set. + */ + public void setText(String text) + { + this.text = text; + } + + public Page getPage() + { + return page; + } + + public void setPage(Page page) { + this.page = page; + } + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Residual.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Residual.java new file mode 100644 index 00000000..08c5f7aa --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Residual.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.util.Map; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ResidualNodesCollectionConverterImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ResidualPropertiesCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Felix Meschberger + * + * Note : + * If the annotation are defined on the field declaration, it is mandatory to register the ancestor classes. + * Otherwise, the annotation mapper will not map the fields defined in the ancester classes. + * + */ +@Node +public class Residual +{ + @Field(path=true) private String path; + + private Map elements; + + /** + * @return Returns the elements. + */ + public Map getElements() + { + return elements; + } + /** + * @param elements The elements to set. + */ + public void setElements(Map elements) + { + this.elements = elements; + } + + + @Node(extend=Residual.class) public static class ResidualProperties extends Residual + { + @Collection( jcrName="value*", + collectionConverter=ResidualPropertiesCollectionConverterImpl.class) + private Map elements; + + + } + + @Node(extend=Residual.class) public static class ResidualNodes extends Residual + { + + @Collection( jcrName="value*",collectionConverter=ResidualNodesCollectionConverterImpl.class) + private Map elements; + + + } + + protected Residual() {} + + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/Resource.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Resource.java new file mode 100644 index 00000000..f169b5a4 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/Resource.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import java.io.InputStream; +import java.util.Calendar; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * Java class used to map the jcr node type nt:resource + * @author Lombart Christophe + * + */ + +@Node(jcrType="nt:resource") +public class Resource +{ + + @Field( jcrName="jcr:mimeType") private String mimeType; + @Field( jcrName="jcr:data") private InputStream data; + @Field( jcrName="jcr:lastModified") private Calendar lastModified; + + public InputStream getData() + { + return data; + } + public void setData(InputStream data) + { + this.data = data; + } + + public Calendar getLastModified() + { + return lastModified; + } + public void setLastModified(Calendar lastModified) + { + this.lastModified = lastModified; + } + public String getMimeType() + { + return mimeType; + } + public void setMimeType(String mimeType) + { + this.mimeType = mimeType; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleAnnotedAbstractClass.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleAnnotedAbstractClass.java new file mode 100644 index 00000000..5f091ac1 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleAnnotedAbstractClass.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +@Node +public abstract class SimpleAnnotedAbstractClass { + + @Field(path=true) String path; + @Field String test; + + public String getTest() { + return test; + } + + public void setTest(String test) { + this.test = test; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleAnnotedClass.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleAnnotedClass.java new file mode 100644 index 00000000..81ee5e63 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleAnnotedClass.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + + +@Node +public class SimpleAnnotedClass + extends SimpleAnnotedAbstractClass // The ancestor is also a mapped class + implements + // The following interface is also mapped + SimpleInterface, + // The following interface is not mapped.So, the ObjectContentManager will not manage it + UnmappedInterface { + + private int testInt; + + public int getTestInt() { + return testInt; + } + + public void setTestInt(int testInt) { + this.testInt = testInt; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleInterface.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleInterface.java new file mode 100644 index 00000000..c7081859 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/SimpleInterface.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public interface SimpleInterface { + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/UnmappedInterface.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/UnmappedInterface.java new file mode 100644 index 00000000..7786520b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/UnmappedInterface.java @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel; + +public interface UnmappedInterface { + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/CmsObject.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/CmsObject.java new file mode 100644 index 00000000..9ea87b1e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/CmsObject.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +@Node(isInterface=true, jcrType="ocm:cmsobject") +public interface CmsObject { + + public String getName(); + + public void setName(String name); + + public String getPath(); + + public void setPath(String path); + + public Folder getParentFolder(); + + public void setParentFolder(Folder parentFolder); + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Content.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Content.java new file mode 100644 index 00000000..f23e812e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Content.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +@Node(isInterface=true, jcrType="ocm:content", extend=CmsObject.class) +public interface Content extends CmsObject { + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Document.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Document.java new file mode 100644 index 00000000..f38563da --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Document.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.auto.impl.DocumentStream; + +@Node(isInterface=true, jcrType="ocm:document", extend=Content.class) +public interface Document extends Content { + + + public String getContentType(); + + public void setContentType(String contentType); + + public long getSize(); + + public void setSize(long size); + + public DocumentStream getDocumentStream(); + + public void setDocumentStream(DocumentStream documentStream); + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Folder.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Folder.java new file mode 100644 index 00000000..b1ad7d56 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/Folder.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto; + +import java.util.List; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isInterface=true, jcrType="ocm:folder", extend=CmsObject.class) +public interface Folder extends CmsObject +{ + + public List getChildren(); + + public void setChildren(List children); + + public void addChild(CmsObject child); + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/CmsObjectImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/CmsObjectImpl.java new file mode 100644 index 00000000..17c13295 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/CmsObjectImpl.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto.impl; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ParentBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.auto.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.auto.Folder; + + + +/** + * CmsObject test + * + * @author Christophe Lombart + * + * + */ +@Node(jcrType="ocm:cmsobjectimpl", discriminator=false, isAbstract=true) +public abstract class CmsObjectImpl implements CmsObject +{ + + @Field(path=true) protected String path; + + @Field(jcrName="ocm:name", id=true) protected String name; + + @Bean(converter=ParentBeanConverterImpl.class) + protected Folder parentFolder; + + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#getName() + */ + public String getName() { + return name; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#setName(java.lang.String) + */ + public void setName(String name) { + this.name = name; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#getPath() + */ + + public String getPath() { + return path; + } + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#setPath(java.lang.String) + */ + public void setPath(String path) { + this.path = path; + } + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#getParentFolder() + */ + + public Folder getParentFolder() { + return parentFolder; + } + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#setParentFolder(org.apache.jackrabbit.ocm.testmodel.interfaces.Folder) + */ + public void setParentFolder(Folder parentFolder) { + this.parentFolder = parentFolder; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/ContentImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/ContentImpl.java new file mode 100644 index 00000000..c8561b23 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/ContentImpl.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto.impl; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.auto.Content; + +/** + * Content implementation + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:contentimpl", isAbstract=true, extend=CmsObjectImpl.class, discriminator=false) +public abstract class ContentImpl extends CmsObjectImpl implements Content +{ +} + + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/DocumentImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/DocumentImpl.java new file mode 100644 index 00000000..8b560850 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/DocumentImpl.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto.impl; + + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.auto.Document; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Document implementation. + * + * @author Christophe Lombart + * + */ + +@Node(jcrType="ocm:documentimpl", extend=ContentImpl.class, discriminator=false) +@Implement(interfaceName=Document.class) +public class DocumentImpl extends ContentImpl implements Document +{ + protected final static Logger log = LoggerFactory.getLogger(DocumentImpl.class); + + @Field(jcrName="ocm:size") protected long size; + @Field(jcrName="ocm:contenttype") protected String contentType; + + @Bean(jcrName="ocm:documentstream", autoUpdate=false, autoInsert=false, autoRetrieve=false ) + protected DocumentStream documentStream; + + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#getContentType() + */ + public String getContentType() + { + return this.contentType; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#setContentType(java.lang.String) + */ + public void setContentType(String contentType) + { + this.contentType = contentType; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#getSize() + */ + public long getSize() + { + return size; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#setSize(long) + */ + public void setSize(long size) + { + this.size = size; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#getDocumentStream() + */ + public DocumentStream getDocumentStream() { + return documentStream; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#setDocumentStream(org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream) + */ + public void setDocumentStream(DocumentStream documentStream) { + this.documentStream = documentStream; + } + + +} + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/DocumentStream.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/DocumentStream.java new file mode 100644 index 00000000..6191d08a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/DocumentStream.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto.impl; + + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Document Content + * + * @author Christophe Lombart + * + */ + +@Node(jcrType="ocm:documentstream", discriminator=false) +public class DocumentStream +{ + protected final static Logger log = LoggerFactory.getLogger(DocumentStream.class); + + @Field( jcrName="ocm:binarycontent") protected byte[] content; + @Field( jcrName="ocm:encoding") protected String encoding; + @Field(path=true) protected String path; + + + /** + * @return Returns the content. + */ + public InputStream getContentStream() + { + return new ByteArrayInputStream(content); + } + + /** + * @return Returns the content. + */ + public byte[] getContent() + { + + return content; + } + + + /** + * @param stream The content to set. + */ + public void setContent(byte[] stream) + { + + content = stream; + + } + + /** + * @return Returns the encoding. + */ + public String getEncoding() + { + return encoding; + } + + /** + * @param encoding The encoding to set. + */ + public void setEncoding(String encoding) + { + this.encoding = encoding; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + +} + + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/FolderImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/FolderImpl.java new file mode 100644 index 00000000..0da6cd87 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/auto/impl/FolderImpl.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.auto.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.NTCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.auto.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.auto.Folder; + +/** + * Forlder implementation + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:folderimpl", extend=CmsObjectImpl.class ,discriminator=false) +@Implement(interfaceName=Folder.class) +public class FolderImpl extends CmsObjectImpl implements Folder +{ + @Collection(proxy=true, autoUpdate=false, autoInsert=false, autoRetrieve=false, + elementClassName=CmsObjectImpl.class, + collectionConverter=NTCollectionConverterImpl.class) + protected List children = new ArrayList(); + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Folder#getChildren() + */ + public List getChildren() { + return children; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Folder#setChildren(java.util.List) + */ + public void setChildren(List children) { + this.children = children; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Folder#addChild(org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject) + */ + public void addChild(CmsObject child) + { + children.add(child); + } +} + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/ArrayListElement.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/ArrayListElement.java new file mode 100644 index 00000000..4eb5d7c7 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/ArrayListElement.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.collection; + +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection; + +/** + * No very useful class. + * This is just there to test custom ManageableCollection implementation + * + * @author Christophe Lombart + * + */ +public class ArrayListElement implements ManageableCollection +{ + + private ArrayList collection = new ArrayList(); + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#addObject(java.lang.Object) + */ + public void addObject(Object object) + { + if (object instanceof Element) + collection.add((Element)object); + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#getIterator() + */ + public Iterator getIterator() + { + return collection.iterator(); + } + + public int getSize() + { + + return collection.size(); + } + + public Object getObjects() { + + return collection; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/CustomList.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/CustomList.java new file mode 100644 index 00000000..fa41b53f --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/CustomList.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.collection; + +import java.util.ArrayList; + +/** + * Don't read the code of this class :-) + * It just there to test a custom collection + */ +public class CustomList extends ArrayList { + + public String getCustomString() + { + StringBuilder customString = new StringBuilder(); + for (Element element : this) + { + customString.append(element.getText()).append(" "); + } + return customString.toString(); + } +} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/Element.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Element.java similarity index 53% rename from src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/Element.java rename to src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Element.java index 0de87e44..ac99ea83 100755 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/Element.java +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Element.java @@ -1,60 +1,66 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel.hashmap; - - -/** - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class Element -{ - private String id; - private String text; - - - /** - * @return Returns the id. - */ - public String getId() - { - return id; - } - /** - * @param id The id to set. - */ - public void setId(String id) - { - this.id = id; - } - /** - * @return Returns the text. - */ - public String getText() - { - return text; - } - /** - * @param text The text to set. - */ - public void setText(String text) - { - this.text = text; - } - - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.collection; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(jcrType="ocm:element", discriminator=false) +public class Element +{ + // an ID field can be used as a unique identifier (for exemple, it can be used as key in a Map) + @Field(jcrName="ocm:id", id=true) private String id; + @Field(jcrName="ocm:text") private String text; + + + /** + * @return Returns the id. + */ + public String getId() + { + return id; + } + /** + * @param id The id to set. + */ + public void setId(String id) + { + this.id = id; + } + /** + * @return Returns the text. + */ + public String getText() + { + return text; + } + /** + * @param text The text to set. + */ + public void setText(String text) + { + this.text = text; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/HashMapElement.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/HashMapElement.java new file mode 100755 index 00000000..ba2d578e --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/HashMapElement.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.collection; + +import java.util.HashMap; +import java.util.Iterator; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableMap; + +/** + * No very useful class. + * This is just there to test custom ManageableMap implementation + * + * @author Christophe Lombart + * + */ +public class HashMapElement implements ManageableMap +{ + + private HashMap map = new HashMap(); + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#addObject(java.lang.Object) + */ + public void addObject(Object object) + { + if (object instanceof Element) + { + map.put(((Element)object).getId(), (Element)object); + } + } + + public void addObject(Object key, Object object) + { + if (object instanceof Element) + { + map.put((String) key, (Element)object); + } + } + + /** + * @see org.apache.jackrabbit.ocm.manager.collectionconverter.ManageableCollection#getIterator() + */ + public Iterator getIterator() + { + return map.values().iterator(); + } + + public int getSize() + { + + return map.size(); + } + + public Object getObjects() + { + return map; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Main.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Main.java new file mode 100755 index 00000000..fb029614 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Main.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.collection; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.BeanReferenceMapConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.uuid.A; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node +public class Main +{ + @Field(path=true) private String path; + + @Field private String text; + @Collection (elementClassName=Element.class) + private HashMapElement hashMapElement; + + @Collection private Map map; + + @Collection(collectionConverter=BeanReferenceMapConverterImpl.class) + private Map referenceMap = new HashMap(); + + + // 3 ways to implements a collection : + + // inherit from ManageableCollection + @Collection (elementClassName=Element.class) + private ArrayListElement arrayListElement; + + // standard collection with Type - no need to specify the elementClassName + @Collection private List list; + + // Custom List + @Collection + private CustomList customList; + + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + /** + * @return Returns the elements. + */ + public HashMapElement getHashMapElement() + { + return hashMapElement; + } + /** + * @param elements The elements to set. + */ + public void setHashMapElement(HashMapElement hashMap) + { + this.hashMapElement = hashMap; + } + + public ArrayListElement getArrayListElement() + { + return arrayListElement; + } + + public void setArrayListElement(ArrayListElement list) + { + this.arrayListElement = list; + } + /** + * @return Returns the text. + */ + public String getText() + { + return text; + } + /** + * @param text The text to set. + */ + public void setText(String text) + { + this.text = text; + } + + public Map getMap() + { + return map; + } + + public void setMap(Map map) + { + this.map = map; + } + + public List getList() { + return list; + } + public void setList(List list) { + this.list = list; + } + public CustomList getCustomList() { + return customList; + } + public void setCustomList(CustomList customList) { + this.customList = customList; + } + public Map getReferenceMap() { + return referenceMap; + } + public void setReferenceMap(Map referenceMap) { + this.referenceMap = referenceMap; + } + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Person.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Person.java new file mode 100644 index 00000000..4b7c9484 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/collection/Person.java @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jackrabbit.ocm.testmodel.collection; + +import java.util.List; +import java.util.Map; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(jcrMixinTypes="mix:referenceable") +public class Person { + @Field(uuid=true) String id; + @Field(jcrName="personName") String name; + @Field(path=true) String path; + @Collection List children; + @Collection Map friends; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public List getChildren() { + return children; + } + public void setChildren(List children) { + this.children = children; + } + public Map getFriends() { + return friends; + } + public void setFriends(Map friends) { + this.friends = friends; + } + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Person other = (Person) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/crossreference/A.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/crossreference/A.java new file mode 100644 index 00000000..7b169506 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/crossreference/A.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.crossreference; + +import java.util.ArrayList; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * + */ +@Node(jcrType="nt:unstructured", jcrMixinTypes="mix:referenceable") +public class A +{ + @Field(path=true) private String path; + @Field(uuid=true) private String uuid; + @Field private String a1; + @Field private String a2; + @Bean private B b; + + @Collection(elementClassName=B.class) + java.util.Collection collection; + + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + /** + * @return Returns the a1. + */ + public String getA1() + { + return a1; + } + /** + * @param a1 The a1 to set. + */ + public void setA1(String a1) + { + this.a1 = a1; + } + /** + * @return Returns the a2. + */ + public String getA2() + { + return a2; + } + /** + * @param a2 The a2 to set. + */ + public void setA2(String a2) + { + this.a2 = a2; + } + /** + * @return Returns the b. + */ + public B getB() + { + return b; + } + /** + * @param b The b to set. + */ + public void setB(B b) + { + this.b = b; + } + + + /** + * @return Returns the collection. + */ + public java.util.Collection getCollection() + { + return collection; + } + + /** + * @param collection The collection to set. + */ + public void setCollection(java.util.Collection collection) + { + this.collection = collection; + } + + public void addB(B b) + { + if (collection == null ) + { + collection = new ArrayList(); + } + + collection.add(b); + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/crossreference/B.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/crossreference/B.java new file mode 100644 index 00000000..8b597cbe --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/crossreference/B.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.crossreference; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ReferenceBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * + * @author Lombart Christophe + * + */ + +@Node +public class B +{ + @Field private String b1; + @Field private String b2; + @Bean(converter=ReferenceBeanConverterImpl.class)private A a; + + + /** + * @return Returns the b1. + */ + public String getB1() + { + return b1; + } + /** + * @param b1 The b1 to set. + */ + public void setB1(String b1) + { + this.b1 = b1; + } + /** + * @return Returns the b2. + */ + public String getB2() + { + return b2; + } + /** + * @param b2 The b2 to set. + */ + public void setB2(String b2) + { + this.b2 = b2; + } + public A getA() { + return a; + } + public void setA(A a) { + this.a = a; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/enumeration/Odyssey.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/enumeration/Odyssey.java new file mode 100644 index 00000000..507f3ac0 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/enumeration/Odyssey.java @@ -0,0 +1,177 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.enumeration; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.EnumCollectionConverterImpl; +import org.apache.jackrabbit.ocm.manager.enumconverter.EnumTypeConverter; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public class Odyssey { + @Field(path=true) + private String path = null; + @Field(converter=EnumTypeConverter.class) + private Planet startingFrom; + @Field(converter=EnumTypeConverter.class) + private Planet goingTo; + public Odyssey(){ + startingFrom = Planet.EARTH; + goingTo = Planet.PLUTO; + stops = new ArrayList(); + } + @org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection(collectionConverter=EnumCollectionConverterImpl.class) + private java.util.List stops; + + public void add(int index, Planet element) { + stops.add(index, element); + } + + public boolean add(Planet e) { + return stops.add(e); + } + + public boolean addAll(Collection c) { + return stops.addAll(c); + } + + public boolean addAll(int index, Collection c) { + return stops.addAll(index, c); + } + + public void clear() { + stops.clear(); + } + + public boolean contains(Object o) { + return stops.contains(o); + } + + public boolean containsAll(Collection c) { + return stops.containsAll(c); + } + + public boolean equals(Object o) { + return stops.equals(o); + } + + public Planet get(int index) { + return stops.get(index); + } + + public int hashCode() { + return stops.hashCode(); + } + + public int indexOf(Object o) { + return stops.indexOf(o); + } + + public boolean isEmpty() { + return stops.isEmpty(); + } + + public Iterator iterator() { + return stops.iterator(); + } + + public int lastIndexOf(Object o) { + return stops.lastIndexOf(o); + } + + public ListIterator listIterator() { + return stops.listIterator(); + } + + public ListIterator listIterator(int index) { + return stops.listIterator(index); + } + + public Planet remove(int index) { + return stops.remove(index); + } + + public boolean remove(Object o) { + return stops.remove(o); + } + + public boolean removeAll(Collection c) { + return stops.removeAll(c); + } + + public boolean retainAll(Collection c) { + return stops.retainAll(c); + } + + public Planet set(int index, Planet element) { + return stops.set(index, element); + } + + public int size() { + return stops.size(); + } + + public List subList(int fromIndex, int toIndex) { + return stops.subList(fromIndex, toIndex); + } + + public Object[] toArray() { + return stops.toArray(); + } + + public T[] toArray(T[] a) { + return stops.toArray(a); + } + + public java.util.List getStops() { + return stops; + } + + public void setStops(java.util.List stops) { + this.stops = stops; + } + + public Planet getStartingFrom() { + return startingFrom; + } + + public void setStartingFrom(Planet startingFrom) { + this.startingFrom = startingFrom; + } + + public Planet getGoingTo() { + return goingTo; + } + + public void setGoingTo(Planet goingTo) { + this.goingTo = goingTo; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/enumeration/Planet.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/enumeration/Planet.java new file mode 100644 index 00000000..4a7e9302 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/enumeration/Planet.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.enumeration; + +public enum Planet { + MERCURY (3.303e+23, 2.4397e6), + VENUS (4.869e+24, 6.0518e6), + EARTH (5.976e+24, 6.37814e6), + MARS (6.421e+23, 3.3972e6), + JUPITER (1.9e+27, 7.1492e7), + SATURN (5.688e+26, 6.0268e7), + URANUS (8.686e+25, 2.5559e7), + NEPTUNE (1.024e+26, 2.4746e7), + PLUTO (1.27e+22, 1.137e6); + + private final double mass; // in kilograms + private final double radius; // in meters + Planet(double mass, double radius) { + this.mass = mass; + this.radius = radius; + } + public double mass() { return mass; } + public double radius() { return radius; } + + // universal gravitational constant (m3 kg-1 s-2) + public static final double G = 6.67300E-11; + + public double surfaceGravity() { + return G * mass / (radius * radius); + } + public double surfaceWeight(double otherMass) { + return otherMass * surfaceGravity(); + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/Ancestor.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/Ancestor.java new file mode 100644 index 00000000..538011e0 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/Ancestor.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isAbstract=true) +public class Ancestor +{ + @Field(path=true)protected String path; + @Field protected String ancestorField; + protected String discriminator; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getAncestorField() { + return ancestorField; + } + + public void setAncestorField(String ancestorField) { + this.ancestorField = ancestorField; + } + + public String getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(String discriminator) { + this.discriminator = discriminator; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/AnotherDescendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/AnotherDescendant.java new file mode 100644 index 00000000..b12ef9d8 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/AnotherDescendant.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; + +@Node(extend=Ancestor.class) +@Implement(interfaceName=Interface.class) +public class AnotherDescendant extends Ancestor implements Interface +{ + + @Field protected String anotherDescendantField; + + public String getAnotherDescendantField() { + return anotherDescendantField; + } + + public void setAnotherDescendantField(String anotherDescendantField) { + this.anotherDescendantField = anotherDescendantField; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/Descendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/Descendant.java new file mode 100644 index 00000000..10f07dd9 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/Descendant.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.AnotherInterface; + +@Node(extend=Ancestor.class) +@Implement(interfaceName=AnotherInterface.class) +public class Descendant extends Ancestor implements AnotherInterface { + + @Field protected String descendantField; + @Field protected int intField; + + + public String getDescendantField() { + return descendantField; + } + + public void setDescendantField(String descendantField) { + this.descendantField = descendantField; + } + + public int getIntField() { + return intField; + } + + public void setIntField(int intField) { + this.intField = intField; + } + + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/SubDescendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/SubDescendant.java new file mode 100644 index 00000000..b417dd06 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/SubDescendant.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +@Node(extend=Descendant.class) + +public class SubDescendant extends Descendant { + + @Field protected String subDescendantField; + + public String getSubDescendantField() { + return subDescendantField; + } + + public void setSubDescendantField(String subDescendantField) { + this.subDescendantField = subDescendantField; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/CmsObjectImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/CmsObjectImpl.java new file mode 100644 index 00000000..502b5e33 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/CmsObjectImpl.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.impl; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ParentBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; + + + +/** + * CmsObject test + * + * @author Christophe Lombart + * + * + */ +@Node(jcrType="ocm:cmsobjectimpl", discriminator=false, isAbstract=true) +@Implement(interfaceName=CmsObject.class) +public class CmsObjectImpl implements CmsObject +{ + + @Field(path=true) protected String path; + @Field(jcrName="ocm:name", id=true) protected String name; + @Bean(converter=ParentBeanConverterImpl.class) protected Folder parentFolder; + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#getName() + */ + public String getName() { + return name; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#setName(java.lang.String) + */ + public void setName(String name) { + this.name = name; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#getPath() + */ + public String getPath() { + return path; + } + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#setPath(java.lang.String) + */ + public void setPath(String path) { + this.path = path; + } + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#getParentFolder() + */ + public Folder getParentFolder() { + return parentFolder; + } + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject#setParentFolder(org.apache.jackrabbit.ocm.testmodel.interfaces.Folder) + */ + public void setParentFolder(Folder parentFolder) { + this.parentFolder = parentFolder; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/ContentImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/ContentImpl.java new file mode 100644 index 00000000..f2532964 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/ContentImpl.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.impl; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Content; + +/** + * Content object + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:contentimpl", isAbstract=true, extend=CmsObjectImpl.class, discriminator=false ) +@Implement(interfaceName=Content.class) +public abstract class ContentImpl extends CmsObjectImpl implements Content +{ +} + + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentExtImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentExtImpl.java new file mode 100644 index 00000000..85f76d72 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentExtImpl.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.impl; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * Simple extension to the DocumentImpl class + */ +@Node(jcrType="ocm:documentextimpl", extend=DocumentImpl.class, discriminator=false) +public class DocumentExtImpl extends DocumentImpl { + + @Field(jcrName="ocm:extinfo") private String extInfo; + + public String getExtInfo() { + return extInfo; + } + + public void setExtInfo(String extInfo) { + this.extInfo = extInfo; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentImpl.java new file mode 100644 index 00000000..fb62fc85 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentImpl.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.impl; + + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Document; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * CMS VersionnedDocument implementation. + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:documentimpl", extend=ContentImpl.class, discriminator=false) +@Implement(interfaceName=Document.class) +public class DocumentImpl extends ContentImpl implements Document +{ + protected final static Logger log = LoggerFactory.getLogger(DocumentImpl.class); + + @Field(jcrName="ocm:size") protected long size; + @Field(jcrName="ocm:contenttype") protected String contentType; + + @Bean(jcrName="ocm:documentstream", proxy=true) protected DocumentStream documentStream; + + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#getContentType() + */ + public String getContentType() + { + return this.contentType; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#setContentType(java.lang.String) + */ + public void setContentType(String contentType) + { + this.contentType = contentType; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#getSize() + */ + public long getSize() + { + return size; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#setSize(long) + */ + public void setSize(long size) + { + this.size = size; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#getDocumentStream() + */ + public DocumentStream getDocumentStream() { + return documentStream; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Document#setDocumentStream(org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream) + */ + public void setDocumentStream(DocumentStream documentStream) { + this.documentStream = documentStream; + } + + +} + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentStream.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentStream.java new file mode 100644 index 00000000..fd918c63 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/DocumentStream.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.impl; + + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + +/** + * Document Steam + * + * @author Christophe Lombart + * + */ +@Node(jcrType="ocm:documentstream", discriminator=false) +public class DocumentStream +{ + protected final static Logger log = LoggerFactory.getLogger(DocumentStream.class); + + @Field(jcrName="ocm:binarycontent") protected byte[] content; + + @Field(jcrName="ocm:encoding") protected String encoding; + + @Field(path=true) protected String path; + + + /** + * @return Returns the content. + */ + public InputStream getContentStream() + { + return new ByteArrayInputStream(content); + } + + /** + * @return Returns the content. + */ + public byte[] getContent() + { + + return content; + } + + + /** + * @param stream The content to set. + */ + public void setContent(byte[] stream) + { + + content = stream; + + } + + /** + * @return Returns the encoding. + */ + public String getEncoding() + { + return encoding; + } + + /** + * @param encoding The encoding to set. + */ + public void setEncoding(String encoding) + { + this.encoding = encoding; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + +} + + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/FolderImpl.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/FolderImpl.java new file mode 100644 index 00000000..85d300af --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/impl/FolderImpl.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.NTCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Folder; + +/** + * CMS Folder Test + * + * @author Christophe Lombart + * @version $Id: Folder.java,v 1.1 2004/12/22 20:36:59 christophe Exp $ + */ +@Node(jcrType="ocm:folderimpl" , extend=CmsObjectImpl.class, discriminator=false) +@Implement(interfaceName=Folder.class) +public class FolderImpl extends CmsObjectImpl implements Folder +{ + + @Collection(proxy=true, + elementClassName=CmsObjectImpl.class, collectionConverter=NTCollectionConverterImpl.class) + protected List children = new ArrayList(); + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Folder#getChildren() + */ + public List getChildren() { + return children; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Folder#setChildren(java.util.List) + */ + public void setChildren(List children) { + this.children = children; + } + + /** + * + * @see org.apache.jackrabbit.ocm.testmodel.interfaces.Folder#addChild(org.apache.jackrabbit.ocm.testmodel.interfaces.CmsObject) + */ + public void addChild(CmsObject child) + { + children.add(child); + } +} + diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/Ancestor.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/Ancestor.java new file mode 100644 index 00000000..63778d97 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/Ancestor.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isAbstract=true,jcrMixinTypes="mix:referenceable") +public class Ancestor +{ + @Field(path=true)protected String path; + @Field protected String ancestorField; + protected String discriminator; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getAncestorField() { + return ancestorField; + } + + public void setAncestorField(String ancestorField) { + this.ancestorField = ancestorField; + } + + public String getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(String discriminator) { + this.discriminator = discriminator; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/AnotherDescendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/AnotherDescendant.java new file mode 100644 index 00000000..bfabd59b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/AnotherDescendant.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.Interface; + +@Node(extend=Ancestor.class) +@Implement(interfaceName=Interface.class) +public class AnotherDescendant extends Ancestor implements Interface +{ + + @Field protected String anotherDescendantField; + + public String getAnotherDescendantField() { + return anotherDescendantField; + } + + public void setAnotherDescendantField(String anotherDescendantField) { + this.anotherDescendantField = anotherDescendantField; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/Descendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/Descendant.java new file mode 100644 index 00000000..9a6bd6be --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/Descendant.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Implement; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.interfaces.AnotherInterface; + +@Node(extend=Ancestor.class) +@Implement(interfaceName=AnotherInterface.class) +public class Descendant extends Ancestor implements AnotherInterface { + + @Field protected String descendantField; + @Field protected int intField; + + + public String getDescendantField() { + return descendantField; + } + + public void setDescendantField(String descendantField) { + this.descendantField = descendantField; + } + + public int getIntField() { + return intField; + } + + public void setIntField(int intField) { + this.intField = intField; + } + + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/SubDescendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/SubDescendant.java new file mode 100644 index 00000000..b17c878a --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/inheritance/withmixin/SubDescendant.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.inheritance.withmixin; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +@Node(extend=Descendant.class) + +public class SubDescendant extends Descendant { + + @Field protected String subDescendantField; + + public String getSubDescendantField() { + return subDescendantField; + } + + public void setSubDescendantField(String subDescendantField) { + this.subDescendantField = subDescendantField; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/AnotherInterface.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/AnotherInterface.java new file mode 100644 index 00000000..56908a3f --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/AnotherInterface.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isInterface=true) +public interface AnotherInterface +{ + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/CmsObject.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/CmsObject.java new file mode 100644 index 00000000..a9fabebe --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/CmsObject.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isInterface=true, jcrType="ocm:cmsobject", discriminator=false ) +public interface CmsObject { + + public String getName(); + + public void setName(String name); + + public String getPath(); + + public void setPath(String path); + + public Folder getParentFolder(); + + public void setParentFolder(Folder parentFolder); + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Content.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Content.java new file mode 100644 index 00000000..3f7cce40 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Content.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isInterface=true, extend= CmsObject.class, jcrType="ocm:content", discriminator=false ) +public interface Content extends CmsObject { + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Document.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Document.java new file mode 100644 index 00000000..06fe9ff2 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Document.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; +import org.apache.jackrabbit.ocm.testmodel.inheritance.impl.DocumentStream; + +@Node(isInterface=true, extend= Content.class, jcrType="ocm:document", discriminator=false ) +public interface Document extends Content { + + + public String getContentType(); + + public void setContentType(String contentType); + + public long getSize(); + + public void setSize(long size); + + public DocumentStream getDocumentStream(); + + public void setDocumentStream(DocumentStream documentStream); + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/EntityA.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/EntityA.java new file mode 100644 index 00000000..0811e067 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/EntityA.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + + +import java.util.List; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public class EntityA { + @Field(path=true) String path; + @Collection List entityB; + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + public List getEntityB() { + return entityB; + } + public void setEntityB(List entityB) { + this.entityB = entityB; + } +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/EntityB.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/EntityB.java new file mode 100644 index 00000000..5d00a9d8 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/EntityB.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public class EntityB implements MyInterface { + @Field private String name; + @Field private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Folder.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Folder.java new file mode 100644 index 00000000..940fbc1b --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Folder.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import java.util.List; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isInterface=true, extend= CmsObject.class, jcrType="ocm:folder", discriminator=false ) +public interface Folder extends CmsObject{ + + public List getChildren(); + + public void setChildren(List children); + + public void addChild(CmsObject child); + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Interface.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Interface.java new file mode 100644 index 00000000..50f49f63 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/Interface.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(isInterface=true) +public interface Interface +{ + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/MyInterface.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/MyInterface.java new file mode 100644 index 00000000..ba1710e3 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/interfaces/MyInterface.java @@ -0,0 +1,24 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.interfaces; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public interface MyInterface { + public String getId(); +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/Detail.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/Detail.java new file mode 100644 index 00000000..1fca4aff --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/Detail.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.proxy; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public class Detail +{ + @Field(path=true) private String path; + @Field private String field; + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/Main.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/Main.java new file mode 100644 index 00000000..aa9c99a3 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/Main.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.proxy; + + + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node +public class Main +{ + + @Field(path=true) private String path; + @Bean(proxy=true) private Detail proxyDetail; + @Bean(proxy=true) private Detail nullDetail; + @Bean private Detail detail; + @Collection(proxy=true, elementClassName=Detail.class) private java.util.Collection proxyCollection; + @Collection(proxy=true, elementClassName=Detail.class) private java.util.Collection nullProxyCollection; + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public Detail getDetail() { + return detail; + } + + public void setDetail(Detail detail) { + this.detail = detail; + } + + public Detail getProxyDetail() { + return proxyDetail; + } + + public void setProxyDetail(Detail proxyDetail) { + this.proxyDetail = proxyDetail; + } + + public Detail getNullDetail() { + return nullDetail; + } + + public void setNullDetail(Detail nullDetail) { + this.nullDetail = nullDetail; + } + + public java.util.Collection getProxyCollection() { + return proxyCollection; + } + + public void setProxyCollection(java.util.Collection proxyCollection) { + this.proxyCollection = proxyCollection; + } + + public java.util.Collection getNullProxyCollection() { + return nullProxyCollection; + } + + public void setNullProxyCollection(java.util.Collection nullProxyCollection) { + this.nullProxyCollection = nullProxyCollection; + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/NTDetail.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/NTDetail.java new file mode 100644 index 00000000..6a079793 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/NTDetail.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.proxy; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(jcrType="ocm:ntdetail") +public class NTDetail +{ + @Field(path=true) private String path; + @Field(jcrName="ocm:field") private String field; + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/NTMain.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/NTMain.java new file mode 100644 index 00000000..14b97516 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/proxy/NTMain.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.proxy; + + + +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.NTCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(jcrType="ocm:ntmain") +public class NTMain +{ + + @Field(path=true) private String path; + @Collection(proxy=true, elementClassName=NTDetail.class,collectionConverter=NTCollectionConverterImpl.class) private java.util.Collection proxyCollection; + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public java.util.Collection getProxyCollection() { + return proxyCollection; + } + + public void setProxyCollection(java.util.Collection proxyCollection) { + this.proxyCollection = proxyCollection; + } + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/unstructured/UnstructuredPage.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/unstructured/UnstructuredPage.java new file mode 100644 index 00000000..56e59403 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/unstructured/UnstructuredPage.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.unstructured; + +import java.util.ArrayList; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * This pojo is mapped into node type "nt:unstructured" and the mixin node type "mix:versionable" + * @author Christophe Lombart + * + */ +@Node(jcrMixinTypes = "mix:versionable") +public class UnstructuredPage +{ + @Field(path=true) String path; + @Field String title; + + @Collection(elementClassName=UnstructuredParagraph.class) + java.util.Collection paragraphs; + + public String getPath() + { + return path; + } + public void setPath(String path) + { + this.path = path; + } + /** + * @return Returns the paragraphs. + */ + public java.util.Collection getParagraphs() + { + return paragraphs; + } + /** + * @param paragraphs The paragraphs to set. + */ + public void setParagraphs(java.util.Collection paragraphs) + { + this.paragraphs = paragraphs; + } + /** + * @return Returns the title. + */ + public String getTitle() + { + return title; + } + /** + * @param title The title to set. + */ + public void setTitle(String title) + { + this.title = title; + } + + public void addParagraph(UnstructuredParagraph paragraph) + { + if (paragraphs == null) + { + paragraphs = new ArrayList(); + } + + paragraphs.add(paragraph); + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/unstructured/UnstructuredParagraph.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/unstructured/UnstructuredParagraph.java new file mode 100644 index 00000000..2728e7cf --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/unstructured/UnstructuredParagraph.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.unstructured; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ParentBeanConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +/** + * This pojo is mapped into node type "nt:unstructured" and the mixin node type "mix:versionable" + * + * @author Christophe Lombart + * + */ +@Node(jcrMixinTypes = "mix:versionable") +public class UnstructuredParagraph +{ + @Field(path=true) private String path; + @Field private String text; + + // The converter ParentBeanConverterImpl can be used to have a simple reference + // to the page containing this pararaph (parent node) - cannot be updated + @Bean(proxy=true, converter=ParentBeanConverterImpl.class) private UnstructuredPage page; + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public UnstructuredParagraph() + { + this.text = "Default text"; + } + + public UnstructuredParagraph(String text) + { + this.text = text; + } + + /** + * @return Returns the text. + */ + public String getText() + { + return text; + } + + /** + * @param text The text to set. + */ + public void setText(String text) + { + this.text = text; + } + + public UnstructuredPage getPage() + { + return page; + } + + public void setPage(UnstructuredPage page) { + this.page = page; + } + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/A.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/A.java new file mode 100644 index 00000000..91be5de2 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/A.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.uuid; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(jcrMixinTypes="mix:referenceable") +public class A +{ + @Field(path=true) private String path; + @Field(uuid=true) private String uuid; + @Field private String stringData; + + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getStringData() { + return stringData; + } + + public void setStringData(String stringData) { + this.stringData = stringData; + } + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/Ancestor.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/Ancestor.java new file mode 100644 index 00000000..150a2a9c --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/Ancestor.java @@ -0,0 +1,53 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.uuid; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(isAbstract=true, jcrMixinTypes="mix:referenceable") +public class Ancestor +{ + @Field(path=true) private String path; + @Field(uuid=true) private String uuid; + + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/B.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/B.java new file mode 100644 index 00000000..7ffbb921 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/B.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.uuid; + + + +import org.apache.jackrabbit.ocm.manager.atomictypeconverter.impl.ReferenceTypeConverterImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.ReferenceCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node +public class B +{ + @Field(path=true) private String path; + @Field(converter=ReferenceTypeConverterImpl.class) private String reference2A; // This String attribute is mapped to a reference/uuid jcr property + @Collection(collectionConverter=ReferenceCollectionConverterImpl.class ) private java.util.Collection multiReferences; // a collection of references (uuid) + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public String getReference2A() + { + return reference2A; + } + + public void setReference2A(String reference2A) + { + this.reference2A = reference2A; + } + + public java.util.Collection getMultiReferences() { + return multiReferences; + } + + public void setMultiReferences(java.util.Collection multiReferences) { + this.multiReferences = multiReferences; + } + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/B2.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/B2.java new file mode 100644 index 00000000..4bd56fde --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/B2.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.uuid; + +import org.apache.jackrabbit.ocm.manager.beanconverter.impl.ReferenceBeanConverterImpl; +import org.apache.jackrabbit.ocm.manager.collectionconverter.impl.BeanReferenceCollectionConverterImpl; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Collection; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node +public class B2 +{ + @Field(path=true) private String path; + + // This attribute is mapped to a reference jcr property + @Bean(converter=ReferenceBeanConverterImpl.class) private A a; + + // a collection of bean mapped into a list of jcr properties (reference type) + @Collection (collectionConverter=BeanReferenceCollectionConverterImpl.class) + private java.util.Collection multiReferences; + + public String getPath() + { + return path; + } + + public void setPath(String path) + { + this.path = path; + } + + public A getA() { + return a; + } + + public void setA(A a) { + this.a = a; + } + public java.util.Collection getMultiReferences() { + return multiReferences; + } + + public void setMultiReferences(java.util.Collection multiReferences) { + this.multiReferences = multiReferences; + } + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/Descendant.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/Descendant.java new file mode 100644 index 00000000..1509e650 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/uuid/Descendant.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.uuid; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + + +/** + * + * @author Lombart Christophe + * @version $Id: Exp $ + */ +@Node(extend=Ancestor.class, jcrMixinTypes="mix:referenceable") +public class Descendant extends Ancestor +{ + + @Field private String stringData; + + + public String getStringData() { + return stringData; + } + + public void setStringData(String stringData) { + this.stringData = stringData; + } + + + + +} diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/version/Author.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/version/Author.java new file mode 100644 index 00000000..c3530a99 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/version/Author.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.version; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(jcrMixinTypes = "mix:versionable") +public class Author { + + //@Field(path = true) String path; + @Field String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +// public String getPath() { +// return path; +// } +// +// public void setPath(String path) { +// this.path = path; +// } + +} \ No newline at end of file diff --git a/src/test/java/org/apache/jackrabbit/ocm/testmodel/version/PressRelease.java b/src/test/java/org/apache/jackrabbit/ocm/testmodel/version/PressRelease.java new file mode 100644 index 00000000..6b9ea8c0 --- /dev/null +++ b/src/test/java/org/apache/jackrabbit/ocm/testmodel/version/PressRelease.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jackrabbit.ocm.testmodel.version; + +import java.util.Date; + +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Bean; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Field; +import org.apache.jackrabbit.ocm.mapper.impl.annotation.Node; + +@Node(jcrMixinTypes = "mix:versionable") +public class PressRelease { + @Field(path = true) String path; + @Field String title; + @Field Date pubDate; + @Field String content; + @Bean Author author; + + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public Date getPubDate() { + return pubDate; + } + + public void setPubDate(Date pubDate) { + this.pubDate = pubDate; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Author getAuthor() { + return author; + } + + public void setAuthor(Author author) { + this.author = author; + } + +} diff --git a/src/test/log4j.properties b/src/test/log4j.properties deleted file mode 100644 index b5d13327..00000000 --- a/src/test/log4j.properties +++ /dev/null @@ -1,38 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ - -# ------------------------------------------------------------------------ -# -# Logging Configuration -# -# $Id: Log4j.properties,v 1.3 2004/12/22 20:37:04 christophe Exp $ -# -# ------------------------------------------------------------------------ - -log4j.rootLogger = WARN, console - -log4j.category.org.apache.portals.graffito.jcr= DEBUG, console -log4j.additivity.org.apache.portals.graffito.jcr=false - -# -# Console -# -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.layout=org.apache.log4j.PatternLayout - -# Pattern to output the caller's file name and line number. -log4j.appender.console.layout.ConversionPattern=%5p: %m%n \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/TestBase.java b/src/test/org/apache/portals/graffito/jcr/TestBase.java deleted file mode 100644 index f5e91713..00000000 --- a/src/test/org/apache/portals/graffito/jcr/TestBase.java +++ /dev/null @@ -1,227 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; - -import javax.jcr.ImportUUIDBehavior; -import javax.jcr.Repository; -import javax.jcr.Session; -import javax.jcr.UnsupportedRepositoryOperationException; - -import junit.framework.TestCase; - -import org.apache.portals.graffito.jcr.exception.RepositoryException; -import org.apache.portals.graffito.jcr.mapper.impl.DigesterMapperImpl; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.BinaryTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.BooleanTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.ByteArrayTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.CalendarTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.DoubleTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.IntTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.LongTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.StringTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.TimestampTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.impl.UtilDateTypeConverterImpl; -import org.apache.portals.graffito.jcr.persistence.impl.PersistenceManagerImpl; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.query.impl.QueryManagerImpl; -import org.apache.portals.graffito.jcr.repository.RepositoryUtil; -import org.xml.sax.ContentHandler; - -/** - * Base class for testcases. Provides priviledged access to the jcr test - * repository. - * - * @author Oliver Kiessler - * @version $Id: Exp $ - */ -public abstract class TestBase extends TestCase -{ - - protected Session session; - - private PersistenceManager persistenceManager; - - private QueryManager queryManager; - - DigesterMapperImpl mapper; - - private static boolean isInit = false; - - /** - *

- * Defines the test case name for junit. - *

- * - * @param testName - * The test case name. - */ - public TestBase(String testName) - { - super(testName); - - try - { - if (!isInit) - { - RepositoryUtil.registerRepository("repositoryTest", "./src/test-config/repository-derby.xml", "./target/repository"); - isInit = true; - } - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Impossible to init the repository"); - } - } - - /** - * Setting up the testcase. - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - super.setUp(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - super.tearDown(); - } - - /** - * Getter for property persistenceManager. - * - * @return jcrSession - */ - public PersistenceManager getPersistenceManager() - { - try - { - if (persistenceManager == null) - { - initPersistenceManager(); - } - return persistenceManager; - } - catch (Exception e) - { - e.printStackTrace(); - return null; - } - } - - protected void initPersistenceManager() throws UnsupportedRepositoryOperationException, javax.jcr.RepositoryException - { - Repository repository = RepositoryUtil.getRepository("repositoryTest"); - String[] files = { "./src/test-config/jcrmapping.xml", "./src/test-config/jcrmapping-atomic.xml" }; - session = RepositoryUtil.login(repository, "superuser", "superuser"); - HashMap atomicTypeConverters = new HashMap(); - atomicTypeConverters.put(String.class, new StringTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(InputStream.class, new BinaryTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(long.class, new LongTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Long.class, new LongTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(int.class, new IntTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Integer.class, new IntTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(double.class, new DoubleTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Double.class, new DoubleTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(boolean.class, new BooleanTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Boolean.class, new BooleanTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Calendar.class, new CalendarTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(GregorianCalendar.class, new CalendarTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Date.class, new UtilDateTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(byte[].class, new ByteArrayTypeConverterImpl(session.getValueFactory())); - atomicTypeConverters.put(Timestamp.class, new TimestampTypeConverterImpl(session.getValueFactory())); - - mapper = new DigesterMapperImpl(files); - queryManager = new QueryManagerImpl(mapper, atomicTypeConverters); - persistenceManager = new PersistenceManagerImpl(mapper, atomicTypeConverters, queryManager, session); - - } - - /** - * Setter for property jcrSession. - * - * @param persistenceManager - * The persistence manager - */ - public void setPersistenceManager(PersistenceManager persistenceManager) - { - this.persistenceManager = persistenceManager; - } - - public void exportDocument(String filePath, String nodePath, boolean skipBinary, boolean noRecurse) - { - try - { - BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(filePath)); - ContentHandler handler = new org.apache.xml.serialize.XMLSerializer(os, null).asContentHandler(); - session.exportDocumentView(nodePath, handler, skipBinary, noRecurse); - os.flush(); - os.close(); - } - catch (Exception e) - { - System.out.println("Impossible to export the content from : " + nodePath); - e.printStackTrace(); - } - } - - public void importDocument(String filePath, String nodePath) - { - try - { - BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath)); - session.importXML(nodePath, is, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW); - session.save(); - is.close(); - } - catch (Exception e) - { - System.out.println("Impossible to import the content from : " + nodePath); - e.printStackTrace(); - } - - } - - protected Session getSession() - { - return this.session; - } - - public QueryManager getQueryManager() - { - return this.queryManager; - } - -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/mapper/DigesterMapperImplTest.java b/src/test/org/apache/portals/graffito/jcr/mapper/DigesterMapperImplTest.java deleted file mode 100644 index 16e4e3c5..00000000 --- a/src/test/org/apache/portals/graffito/jcr/mapper/DigesterMapperImplTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.mapper; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.portals.graffito.jcr.exception.JcrMappingException; -import org.apache.portals.graffito.jcr.mapper.impl.DigesterMapperImpl; -import org.apache.portals.graffito.jcr.mapper.model.BeanDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.ClassDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.CollectionDescriptor; -import org.apache.portals.graffito.jcr.mapper.model.FieldDescriptor; -import org.apache.portals.graffito.jcr.testmodel.A; -import org.apache.portals.graffito.jcr.testmodel.B; - -/** - * Test Mapper - * - * @author Christophe Lombart - */ -public class DigesterMapperImplTest extends TestCase -{ - - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public DigesterMapperImplTest(String testName) - { - super(testName); - } - - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - super.setUp(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - super.tearDown(); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(DigesterMapperImplTest.class); - } - - /** - * Test for getConverter - * - */ - public void testMapper() - { - try - { - DigesterMapperImpl mapper = new DigesterMapperImpl("./src/test-config/jcrmapping.xml"); - assertNotNull("Mapper is null", mapper); - - ClassDescriptor classDescriptor = mapper.getClassDescriptor(A.class); - assertNotNull("ClassDescriptor is null", classDescriptor); - assertTrue("Invalid classname", classDescriptor.getClassName().equals(A.class.getName())); - assertTrue("Invalid path field", classDescriptor.getPathFieldDescriptor().getFieldName().equals("path")); - - FieldDescriptor fieldDescriptor = classDescriptor.getFieldDescriptor("a1"); - assertNotNull("FieldDescriptor is null", fieldDescriptor); - assertTrue("Invalid jcrName for field a1", fieldDescriptor.getJcrName().equals("a1")); - - BeanDescriptor beanDescriptor = classDescriptor.getBeanDescriptor("b"); - assertNotNull("BeanDescriptor is null", beanDescriptor); - assertTrue("Invalid jcrName for field b", beanDescriptor.getJcrName().equals("b")); - - CollectionDescriptor collectionDescriptor = classDescriptor.getCollectionDescriptor("collection"); - assertNotNull("CollectionDescriptor is null", collectionDescriptor); - assertTrue("Invalid jcrName for field collection", collectionDescriptor.getJcrName().equals("collection")); - } - catch (JcrMappingException e) - { - e.printStackTrace(); - fail("Impossible to retrieve the converter " + e); - } - } - - /** - * Test for getConverter - * - */ - public void testMapperOptionalProperties() - { - try - { - DigesterMapperImpl mapper = new DigesterMapperImpl("./src/test-config/jcrmapping.xml"); - assertNotNull("Mapper is null", mapper); - - ClassDescriptor classDescriptor = mapper.getClassDescriptor(B.class); - assertNotNull("ClassDescriptor is null", classDescriptor); - assertTrue("Invalid classname", classDescriptor.getClassName().equals(B.class.getName())); - assertEquals(classDescriptor.getJcrSuperTypes(), "nt:base"); - - FieldDescriptor b1Field = classDescriptor.getFieldDescriptor("b1"); - assertNotNull("FieldDescriptor is null", b1Field); - assertEquals(b1Field.getFieldName(), "b1"); - assertEquals(b1Field.getJcrType(), "String"); - assertFalse(b1Field.isJcrAutoCreated()); - assertFalse(b1Field.isJcrMandatory()); - assertFalse(b1Field.isJcrProtected()); - assertFalse(b1Field.isJcrMultiple()); - assertEquals(b1Field.getJcrOnParentVersion(), "IGNORE"); - - FieldDescriptor b2Field = classDescriptor.getFieldDescriptor("b2"); - assertNotNull("FieldDescriptor is null", b2Field); - assertEquals(b2Field.getFieldName(), "b2"); - assertEquals(b2Field.getJcrType(), "String"); - assertTrue(b2Field.isJcrAutoCreated()); - assertTrue(b2Field.isJcrMandatory()); - assertTrue(b2Field.isJcrProtected()); - assertTrue(b2Field.isJcrMultiple()); - assertEquals(b2Field.getJcrOnParentVersion(), "COPY"); - - ClassDescriptor classDescriptor2 = mapper.getClassDescriptor(A.class); - assertNotNull("ClassDescriptor is null", classDescriptor2); - assertTrue("Invalid classname", classDescriptor2.getClassName().equals(A.class.getName())); - - BeanDescriptor beanDescriptor = classDescriptor2.getBeanDescriptor("b"); - assertNotNull(beanDescriptor); - assertEquals(beanDescriptor.getFieldName(), "b"); - assertEquals(beanDescriptor.getJcrNodeType(), "nt:unstructured"); - assertFalse(beanDescriptor.isJcrAutoCreated()); - assertFalse(beanDescriptor.isJcrMandatory()); - assertFalse(beanDescriptor.isJcrProtected()); - assertFalse(beanDescriptor.isJcrSameNameSiblings()); - assertEquals(beanDescriptor.getJcrOnParentVersion(), "IGNORE"); - - CollectionDescriptor collectionDescriptor = classDescriptor2.getCollectionDescriptor("collection"); - assertNotNull(collectionDescriptor); - assertEquals(collectionDescriptor.getJcrNodeType(), "graffito:C"); - assertFalse(collectionDescriptor.isJcrAutoCreated()); - assertFalse(collectionDescriptor.isJcrMandatory()); - assertFalse(collectionDescriptor.isJcrProtected()); - assertFalse(collectionDescriptor.isJcrSameNameSiblings()); - assertEquals(collectionDescriptor.getJcrOnParentVersion(), "IGNORE"); - } - catch (JcrMappingException e) - { - e.printStackTrace(); - fail("Impossible to retrieve the converter " + e); - } - } -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerBasicVersionningTest.java b/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerBasicVersionningTest.java deleted file mode 100644 index 4833b2f0..00000000 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerBasicVersionningTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package org.apache.portals.graffito.jcr.persistence.impl; - - -import java.util.Date; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; -import org.apache.portals.graffito.jcr.version.Version; -import org.apache.portals.graffito.jcr.version.VersionIterator; - -/** - * Test Query on atomic fields - * - * @author Christophe Lombart - */ -public class PersistenceManagerBasicVersionningTest extends TestBase -{ - private final static Log log = LogFactory.getLog(PersistenceManagerBasicVersionningTest.class); - private Date date = new Date(); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerBasicVersionningTest(String testName) throws Exception - { - super(testName); - - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerBasicVersionningTest.class); - } - - public void tearDown() throws Exception - { - PersistenceManager persistenceManager = getPersistenceManager(); - persistenceManager.remove("/page"); - persistenceManager.save(); - - super.tearDown(); - } - - public void testSimpleVersion() - { - PersistenceManager persistenceManager = getPersistenceManager(); - try - { - - Page page = new Page(); - page.setPath("/page"); - page.setTitle("Page Title"); - page.addParagraph(new Paragraph("para1")); - page.addParagraph(new Paragraph("para2")); - persistenceManager.insert(page); - persistenceManager.save(); - - - page.addParagraph(new Paragraph("para3")); - persistenceManager.checkout("/page"); - persistenceManager.update(page); - persistenceManager.save(); - persistenceManager.checkin("/page"); - - page.addParagraph(new Paragraph("para4")); - persistenceManager.checkout("/page"); - persistenceManager.update(page); - persistenceManager.save(); - persistenceManager.checkin("/page"); - - VersionIterator versionIterator = persistenceManager.getAllVersions("/page"); - assertNotNull("VersionIterator is null", versionIterator); - assertTrue("Invalid number of versions found", versionIterator.getSize() == 3); - - while (versionIterator.hasNext()) - { - Version version = (Version) versionIterator.next(); - log.info("version found : " + version.getPath() + " - " + version.getCreated().getTime()); - - } - - Version baseVersion = persistenceManager.getBaseVersion("/page"); - System.out.println("Base version : " + baseVersion.getName()); - - Version rootVersion = persistenceManager.getRootVersion("/page"); - System.out.println("Root version : " + rootVersion.getName()); - //this.exportDocument("/home/christophe/export.xml", "/jcr:system/jcr:versionStorage", true, false); - - //Get the object matching to the first version - Page page1 = (Page) persistenceManager.getObject(Page.class, "/page", "1.0"); - assertNotNull("version 1.0 object is null", page1); - assertTrue("Invalid number of paragraph found in the root version", page1.getParagraphs().size() == 3); - - } - catch(Exception e) - { - e.printStackTrace(); - fail(); - - } - } - - - public void testVersionLabels() - { - PersistenceManager persistenceManager = getPersistenceManager(); - try - { - - Page page = new Page(); - page.setPath("/page"); - page.setTitle("Page Title"); - page.addParagraph(new Paragraph("para1")); - page.addParagraph(new Paragraph("para2")); - persistenceManager.insert(page); - persistenceManager.save(); - - - page.addParagraph(new Paragraph("para3")); - persistenceManager.checkout("/page"); - persistenceManager.update(page); - persistenceManager.save(); - persistenceManager.checkin("/page", new String[] {"A", "B"}); - - page.addParagraph(new Paragraph("para4")); - persistenceManager.checkout("/page"); - persistenceManager.update(page); - persistenceManager.save(); - persistenceManager.checkin("/page", new String[] {"C", "D"}); - - String[] allLabels = persistenceManager.getAllVersionLabels("/page"); - assertTrue("Incorrect number of labels", allLabels.length == 4); - - String[] versionLabels = persistenceManager.getVersionLabels("/page", "1.1"); - assertTrue("Incorrect number of labels", versionLabels.length == 2); - assertTrue("Incorrect label", versionLabels[0].equals("C") || versionLabels[0].equals("D")); - assertTrue("Incorrect label", versionLabels[1].equals("C") || versionLabels[0].equals("D")); - - - } - catch(Exception e) - { - e.printStackTrace(); - fail(); - } - } - -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerIteratorQueryTest.java b/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerIteratorQueryTest.java deleted file mode 100644 index e0ea1e9d..00000000 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerIteratorQueryTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.Session; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.exception.JcrMappingException; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; - - -/** - * Test Object Iterator - * - * @author Christophe Lombart - */ -public class PersistenceManagerIteratorQueryTest extends TestBase -{ - private final static Log log = LogFactory.getLog(PersistenceManagerIteratorQueryTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerIteratorQueryTest(String testName) throws Exception - { - super(testName); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerIteratorQueryTest.class); - } - - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - super.setUp(); - this.importData(); - - } - - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - - } - getPersistenceManager().save(); - super.tearDown(); - } - - /** - * Test equalTo - * - */ - public void testsetScope() - { - - try - { - - // No scope - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Page.class); - Query query = queryManager.createQuery(filter); - PersistenceManager persistenceManager = this.getPersistenceManager(); - - long start = System.currentTimeMillis(); - Iterator iterator = persistenceManager.getObjectIterator(query); - System.out.println("getObject takes : " + (System.currentTimeMillis() - start)); - - start = System.currentTimeMillis(); - Collection result = persistenceManager.getObjects(query); - System.out.println("getObject takes : " + (System.currentTimeMillis() - start)); - - start = System.currentTimeMillis(); - iterator = persistenceManager.getObjectIterator(query); - System.out.println("getObject takes : " + (System.currentTimeMillis() - start)); - - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - - private void importData() throws JcrMappingException - { - - try - { - PersistenceManager persistenceManager = getPersistenceManager(); - - if (persistenceManager.objectExists("/test")) - { - persistenceManager.remove("/test"); - } - - PersistenceManagerImpl persistenceManagerImpl = (PersistenceManagerImpl) persistenceManager; - - Session session = persistenceManagerImpl.getSession(); - Node root = session.getRootNode(); - root.addNode("test"); - root.addNode("test/node1"); - root.addNode("test/node2"); - - root.save(); - - Page page = new Page(); - page.setPath("/test/node1/page1"); - page.setTitle("Page 1 Title"); - - ArrayList paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 2")); - paragraphs.add(new Paragraph("Para 3")); - paragraphs.add(new Paragraph("Another Para ")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - - - page = new Page(); - page.setPath("/test/node1/page2"); - page.setTitle("Page 2 Title"); - - paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 2")); - paragraphs.add(new Paragraph("Para 5")); - paragraphs.add(new Paragraph("Another Para")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - - page = new Page(); - page.setPath("/test/node2/page1"); - page.setTitle("Page 3 Title"); - - paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 4")); - paragraphs.add(new Paragraph("Para 5")); - paragraphs.add(new Paragraph("Another Para")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - - page = new Page(); - page.setPath("/test/node2/page2"); - page.setTitle("Page 4 Title"); - - paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 6")); - paragraphs.add(new Paragraph("Para 7")); - paragraphs.add(new Paragraph("Para 8")); - paragraphs.add(new Paragraph("Another Para")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - - persistenceManager.save(); - - - - } - catch (RepositoryException e) - { - - e.printStackTrace(); - } - - - } -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerSameNameSiblingTest.java b/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerSameNameSiblingTest.java deleted file mode 100644 index 23c64c28..00000000 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerSameNameSiblingTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.io.ByteArrayInputStream; -import java.sql.Timestamp; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.persistence.atomictypeconverter.AtomicTypeConverter; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.Atomic; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; - -/** - * Test Query on atomic fields - * - * @author Christophe Lombart - */ -public class PersistenceManagerSameNameSiblingTest extends TestBase -{ - private final static Log log = LogFactory.getLog(PersistenceManagerSameNameSiblingTest.class); - private Date date = new Date(); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerSameNameSiblingTest(String testName) throws Exception - { - super(testName); - - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerSameNameSiblingTest.class); - } - - - public void testSameNameSiblings() - { - - try - { - this.importData(date); - PersistenceManager persistenceManager = this.getPersistenceManager(); - - // Query all objects - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Atomic.class); - filter.setScope("/"); - Query query = queryManager.createQuery(filter); - Collection result = persistenceManager.getObjects(query); - assertTrue("Incorrect number of objects found", result.size() == 10); - - // Get objects - Atomic atomic = (Atomic) persistenceManager.getObject(Atomic.class, "/test[2]"); - assertNotNull("Object /test[2] not found", atomic); - - atomic = (Atomic) persistenceManager.getObject(Atomic.class, "/test[10]"); - assertNotNull("Object /test[2] not found", atomic); - - // Update the object - atomic.setString("Modified Test String 10"); - persistenceManager.update(atomic); - persistenceManager.save(); - - // Query on the attribute "string" - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(Atomic.class); - filter.addLike("string", "Modified%"); - query = queryManager.createQuery(filter); - result = persistenceManager.getObjects(query); - assertTrue("Incorrect number of objects found", result.size() == 1); - - atomic = (Atomic) persistenceManager.getObject(query); - assertNotNull("Object not found", atomic); - assertTrue("Incorrect Object", atomic.getString().equals("Modified Test String 10")); - - // Delete all objects - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(Atomic.class); - filter.setScope("/"); - query = queryManager.createQuery(filter) ; - persistenceManager.remove(query); - persistenceManager.save(); - - result = persistenceManager.getObjects(query); - assertTrue("Incorrect number of objects found", result.size() == 0); - - - } - catch (Exception e) - { - e.printStackTrace(); - fail(); - } - - } - - public void testUnsupportedSameNameSiblings() - { - PersistenceManager persistenceManager = getPersistenceManager(); - try - { - - Page page = new Page(); - page.setPath("/page"); - page.setTitle("Page Title"); - persistenceManager.insert(page); - persistenceManager.save(); - - Paragraph p1 = new Paragraph("para1"); - p1.setPath("/page/paragraph"); - persistenceManager.insert(p1); - - Paragraph p2 = new Paragraph("para1"); - p2.setPath("/page/paragraph"); - persistenceManager.insert(p2); - fail(); - - } - catch(Exception e) - { - persistenceManager.remove("/page"); - persistenceManager.save(); - } - } - - - private void importData(Date date) - { - try - { - - PersistenceManager persistenceManager = getPersistenceManager(); - - - for (int i = 1; i <= 10; i++) - { - Atomic a = new Atomic(); - a.setPath("/test"); - a.setBooleanObject(new Boolean(i%2==0)); - a.setBooleanPrimitive(true); - a.setIntegerObject(new Integer(100 * i)); - a.setIntPrimitive(200 + i); - a.setString("Test String " + i); - a.setDate(date); - Calendar calendar = Calendar.getInstance(); - calendar.set(1976, 4, 20, 15, 40); - a.setCalendar(calendar); - a.setDoubleObject(new Double(2.12 + i)); - a.setDoublePrimitive(1.23 + i); - long now = System.currentTimeMillis(); - a.setTimestamp(new Timestamp(now)); - if ((i % 2) == 0) - { - a.setByteArray("This is small object stored in a JCR repository".getBytes()); - a.setInputStream(new ByteArrayInputStream("Test inputstream".getBytes())); - } - else - { - a.setByteArray("This is small object stored in a Graffito repository".getBytes()); - a.setInputStream(new ByteArrayInputStream("Another Stream".getBytes())); - } - persistenceManager.insert(a); - - - } - persistenceManager.save(); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerScopeQueryTest.java b/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerScopeQueryTest.java deleted file mode 100644 index 844f5a1e..00000000 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerScopeQueryTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.util.ArrayList; -import java.util.Collection; - -import javax.jcr.Node; -import javax.jcr.RepositoryException; -import javax.jcr.Session; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.exception.JcrMappingException; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; - - -/** - * Test QueryManagerImpl Query methods - * - * @author Christophe Lombart - */ -public class PersistenceManagerScopeQueryTest extends TestBase -{ - private final static Log log = LogFactory.getLog(PersistenceManagerScopeQueryTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerScopeQueryTest(String testName) throws Exception - { - super(testName); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerScopeQueryTest.class); - } - - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - super.setUp(); - this.importData(); - - } - - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - } - getPersistenceManager().save(); - super.tearDown(); - } - - /** - * Test equalTo - * - */ - public void testsetScope() - { - - try - { - - - PersistenceManager persistenceManager = this.getPersistenceManager(); - // Search on subtree (test/node1) - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Paragraph.class); - filter.setScope("/test/node1//"); - Query query = queryManager.createQuery(filter); - persistenceManager = this.getPersistenceManager(); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 8", result.size() == 8); - - - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(Paragraph.class); - filter.setScope("/test//"); - query = queryManager.createQuery(filter); - persistenceManager = this.getPersistenceManager(); - result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 16", result.size() == 16); - - // Test on children - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(Paragraph.class); - filter.setScope("/test/"); - query = queryManager.createQuery(filter); - persistenceManager = this.getPersistenceManager(); - result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 0", result.size() == 0); - - // Search on scope and properties - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(Paragraph.class); - filter.setScope("/test//"); - filter.addEqualTo("text", "Para 1"); - query = queryManager.createQuery(filter); - persistenceManager = this.getPersistenceManager(); - result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 3", result.size() == 3); - - - queryManager = this.getQueryManager(); - filter = queryManager.createFilter(Paragraph.class); - filter.setScope("/test//"); - filter.addContains("text", "another"); - query = queryManager.createQuery(filter); - persistenceManager = this.getPersistenceManager(); - result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 4", result.size() == 4); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - - private void importData() throws JcrMappingException - { - - try - { - PersistenceManager persistenceManager = getPersistenceManager(); - - PersistenceManagerImpl persistenceManagerImpl = (PersistenceManagerImpl) persistenceManager; - - Session session = persistenceManagerImpl.getSession(); - Node root = session.getRootNode(); - root.addNode("test"); - root.addNode("test/node1"); - root.addNode("test/node2"); - - root.save(); - - Page page = new Page(); - page.setPath("/test/node1/page1"); - page.setTitle("Page 1 Title"); - - ArrayList paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 2")); - paragraphs.add(new Paragraph("Para 3")); - paragraphs.add(new Paragraph("Another Para ")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - - - page = new Page(); - page.setPath("/test/node1/page2"); - page.setTitle("Page 2 Title"); - - paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 2")); - paragraphs.add(new Paragraph("Para 5")); - paragraphs.add(new Paragraph("Another Para")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - - page = new Page(); - page.setPath("/test/node2/page1"); - page.setTitle("Page 3 Title"); - - paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 4")); - paragraphs.add(new Paragraph("Para 5")); - paragraphs.add(new Paragraph("Another Para")); - page.setParagraphs(paragraphs); - - persistenceManager.insert( page); - - page = new Page(); - page.setPath("/test/node2/page2"); - page.setTitle("Page 4 Title"); - - paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 6")); - paragraphs.add(new Paragraph("Para 7")); - paragraphs.add(new Paragraph("Para 8")); - paragraphs.add(new Paragraph("Another Para")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - persistenceManager.save(); - - - } - catch (RepositoryException e) - { - - e.printStackTrace(); - } - - - } -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerSimpleQueryTest.java b/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerSimpleQueryTest.java deleted file mode 100644 index ea2810a0..00000000 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerSimpleQueryTest.java +++ /dev/null @@ -1,278 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.exception.JcrMappingException; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.Page; -import org.apache.portals.graffito.jcr.testmodel.Paragraph; - - -/** - * Test QueryManagerImpl Query methods - * - * @author Christophe Lombart - */ -public class PersistenceManagerSimpleQueryTest extends TestBase -{ - private final static Log log = LogFactory.getLog(PersistenceManagerSimpleQueryTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerSimpleQueryTest(String testName) throws Exception - { - super(testName); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerSimpleQueryTest.class); - } - - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - super.setUp(); - importData(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - - super.tearDown(); - } - - /** - * Test equalTo - * - */ - public void testGetObjectEqualsTo() - { - - try - { - - // Build the Query Object - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Paragraph.class); - filter.addEqualTo("text", "Para 1"); - - - Query query = queryManager.createQuery(filter); - - PersistenceManager persistenceManager = this.getPersistenceManager(); - Paragraph paragraph = (Paragraph) persistenceManager.getObject(query); - assertNotNull("Object is null", paragraph); - assertTrue("Invalid paragraph found" , paragraph.getText().equals("Para 1")); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - /** - * Test equalTo - * - */ - public void testGetObjectsEqualsTo() - { - - try - { - - // Build the Query Object - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Paragraph.class); - filter.addEqualTo("text", "Para 1"); - filter.setScope("/test/"); - - Query query = queryManager.createQuery(filter); - - PersistenceManager persistenceManager = this.getPersistenceManager(); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 1", result.size() == 1); - Paragraph paragraph = (Paragraph) result.iterator().next(); - assertTrue("Invalid paragraph found" , paragraph.getText().equals("Para 1")); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - /** - * Test the like "like" expression - */ - public void testGetObjectsLike() - { - - try - { - - // Build the Query Object - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Paragraph.class); - filter.addLike("text", "Para%"); - filter.setScope("/test/"); - - Query query = queryManager.createQuery(filter); - - PersistenceManager persistenceManager = this.getPersistenceManager(); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 3", result.size() == 3); - - Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); - assertTrue("Invalid paragraph found", paragraphs[0].getText().equals("Para 1")); - assertTrue("Invalid paragraph found", paragraphs[1].getText().equals("Para 2")); - assertTrue("Invalid paragraph found", paragraphs[2].getText().equals("Para 3")); - - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - - /** - * Build an or expression between 2 filters - * - */ - public void testGetObjectsOr() - { - - try - { - - // Build the Query Object - QueryManager queryManager = this.getQueryManager(); - Filter filter1 = queryManager.createFilter(Paragraph.class); - filter1.addEqualTo("text", "Para 1"); - filter1.setScope("/test/"); - - Filter filter2 = queryManager.createFilter(Paragraph.class); - filter2.addEqualTo("text", "Para 2"); - - filter1.addOrFilter(filter2); - - Query query = queryManager.createQuery(filter1); - - PersistenceManager persistenceManager = this.getPersistenceManager(); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 2", result.size() == 2); - - Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); - assertTrue("Invalid paragraph found", paragraphs[0].getText().equals("Para 1")); - assertTrue("Invalid paragraph found", paragraphs[1].getText().equals("Para 2")); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - public void testGetObjectOrderBy() - { - - try - { - - // Build the Query Object - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(Paragraph.class); - filter.addLike("text", "Para%"); - filter.setScope("/test/"); - - Query query = queryManager.createQuery(filter); - query.addOrderByDescending("text"); - - PersistenceManager persistenceManager = this.getPersistenceManager(); - Collection result = persistenceManager.getObjects(query); - assertTrue("Invalid number of objects - should be = 3", result.size() == 3); - - Paragraph[] paragraphs = (Paragraph[]) result.toArray(new Paragraph[result.size()]); - assertTrue("Invalid paragraph found", paragraphs[0].getText().equals("Para 3")); - assertTrue("Invalid paragraph found", paragraphs[1].getText().equals("Para 2")); - assertTrue("Invalid paragraph found", paragraphs[2].getText().equals("Para 1")); - - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - private void importData() throws JcrMappingException - { - PersistenceManager persistenceManager = getPersistenceManager(); - - Page page = new Page(); - page.setPath("/test"); - page.setTitle("Page Title"); - - ArrayList paragraphs = new ArrayList(); - - paragraphs.add(new Paragraph("Para 1")); - paragraphs.add(new Paragraph("Para 2")); - paragraphs.add(new Paragraph("Para 3")); - paragraphs.add(new Paragraph("Another Para ")); - page.setParagraphs(paragraphs); - - persistenceManager.insert(page); - persistenceManager.save(); - - - } -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerTest.java b/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerTest.java deleted file mode 100644 index 65774c7b..00000000 --- a/src/test/org/apache/portals/graffito/jcr/persistence/impl/PersistenceManagerTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.persistence.impl; - -import java.util.ArrayList; -import java.util.Collection; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.persistence.PersistenceManager; -import org.apache.portals.graffito.jcr.testmodel.A; -import org.apache.portals.graffito.jcr.testmodel.B; -import org.apache.portals.graffito.jcr.testmodel.C; - -/** - * Test JcrSession - * - * @author Christophe Lombart - */ -public class PersistenceManagerTest extends TestBase -{ - private final static Log log = LogFactory.getLog(PersistenceManagerTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public PersistenceManagerTest(String testName) throws Exception - { - super(testName); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(PersistenceManagerTest.class); - } - - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - if (getPersistenceManager().objectExists("/test")) - { - getPersistenceManager().remove("/test"); - getPersistenceManager().save(); - } - super.tearDown(); - } - - public void testClassA() - { - try - { - PersistenceManager persistenceManager = getPersistenceManager(); - - - // -------------------------------------------------------------------------------- - // Create and store an object graph in the repository - // -------------------------------------------------------------------------------- - A a = new A(); - a.setPath("/test"); - a.setA1("a1"); - a.setA2("a2"); - B b = new B(); - b.setB1("b1"); - b.setB2("b2"); - a.setB(b); - - C c1 = new C(); - c1.setId("first"); - c1.setName("First Element"); - C c2 = new C(); - c2.setId("second"); - c2.setName("Second Element"); - - C c3 = new C(); - c3.setId("third"); - c3.setName("Third Element"); - - - Collection collection = new ArrayList(); - collection.add(c1); - collection.add(c2); - collection.add(c3); - - a.setCollection(collection); - - persistenceManager.insert(a); - persistenceManager.save(); - - - // -------------------------------------------------------------------------------- - // Get the object - // -------------------------------------------------------------------------------- - a = (A) persistenceManager.getObject(A.class, "/test"); - assertNotNull("a is null", a); - assertTrue("Incorrect a1", a.getA1().equals("a1")); - assertNotNull("a.b is null", a.getB()); - assertTrue("Incorrect a.b.b1", a.getB().getB1().equals("b1")); - assertNotNull("a.collection is null", a.getCollection()); - assertTrue("Incorrect a.collection", ((C) a.getCollection().iterator().next()).getId().equals("first")); - - // -------------------------------------------------------------------------------- - // Update the object - // -------------------------------------------------------------------------------- - a.setA1("new value"); - B newB = new B(); - newB.setB1("new B1"); - newB.setB2("new B2"); - a.setB(newB); - - - persistenceManager.update(a); - persistenceManager.save(); - - // -------------------------------------------------------------------------------- - // Get the object - // -------------------------------------------------------------------------------- - a = (A) persistenceManager.getObject(A.class, "/test"); - assertNotNull("a is null", a); - assertTrue("Incorrect a1", a.getA1().equals("new value")); - assertNotNull("a.b is null", a.getB()); - assertTrue("Incorrect a.b.b1", a.getB().getB1().equals("new B1")); - - - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - public void testIsPersistent() - { - PersistenceManager persistenceManager = getPersistenceManager(); - assertTrue("Class A is not persistent ", persistenceManager.isPersistent(A.class)); - assertFalse("Class String is persistent - hum ? ", persistenceManager.isPersistent(String.class)); - } - - -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/query/impl/QueryManagerTest.java b/src/test/org/apache/portals/graffito/jcr/query/impl/QueryManagerTest.java deleted file mode 100644 index 380ac3ad..00000000 --- a/src/test/org/apache/portals/graffito/jcr/query/impl/QueryManagerTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.query.impl; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.TestBase; -import org.apache.portals.graffito.jcr.query.Filter; -import org.apache.portals.graffito.jcr.query.Query; -import org.apache.portals.graffito.jcr.query.QueryManager; -import org.apache.portals.graffito.jcr.testmodel.C; - - -/** - * Test QueryManagerImpl methods - * - * @author Christophe Lombart - */ -public class QueryManagerTest extends TestBase -{ - private final static Log log = LogFactory.getLog(QueryManagerTest.class); - - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public QueryManagerTest(String testName) throws Exception - { - super(testName); - initPersistenceManager(); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(QueryManagerTest.class); - } - - public void testBuildExpression1() - { - - try - { - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(C.class); - filter.addEqualTo("name", "a test value"); - filter.addEqualTo("id", new Integer(1)); - filter.setScope("/test//"); - - Query query = queryManager.createQuery(filter); - String jcrExpression = queryManager.buildJCRExpression(query); - assertNotNull("jcrExpression is null", jcrExpression); - assertTrue("Invalid JcrExpression", jcrExpression.equals("/jcr:root/test//element(*, graffito:C) [@graffito:name = 'a test value' and @graffito:id = 1]")); - - - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - public void testBuildExpression2() - { - - try - { - QueryManager queryManager = this.getQueryManager(); - Filter filter = queryManager.createFilter(C.class); - filter.addEqualTo("name", "a test value"); - filter.addEqualTo("id", new Integer(1)); - - Query query = queryManager.createQuery(filter); - String jcrExpression = queryManager.buildJCRExpression(query); - assertNotNull("jcrExpression is null", jcrExpression); - assertTrue("Invalid JcrExpression", jcrExpression.equals("//element(*, graffito:C) [@graffito:name = 'a test value' and @graffito:id = 1]")); - - - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Exception occurs during the unit test : " + e); - } - - } - - -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/repository/RepositoryUtilTest.java b/src/test/org/apache/portals/graffito/jcr/repository/RepositoryUtilTest.java deleted file mode 100644 index 2a3a8d82..00000000 --- a/src/test/org/apache/portals/graffito/jcr/repository/RepositoryUtilTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/* ======================================================================== - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ======================================================================== - */ -package org.apache.portals.graffito.jcr.repository; - -import javax.jcr.ItemNotFoundException; -import javax.jcr.Node; -import javax.jcr.Repository; -import javax.jcr.Session; -import javax.jcr.nodetype.NodeTypeManager; -import javax.transaction.UserTransaction; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.portals.graffito.jcr.transaction.jackrabbit.UserTransactionImpl; - -/** Testcase for RepositoryUtil. - * - * @author Christophe Lombart - */ -public class RepositoryUtilTest extends TestCase -{ - private final static Log log = LogFactory.getLog(RepositoryUtilTest.class); - private static boolean isInit = false; - /** - *

Defines the test case name for junit.

- * @param testName The test case name. - */ - public RepositoryUtilTest(String testName) - { - super(testName); - } - - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - super.setUp(); - if (! isInit) - { - RepositoryUtil.registerRepository("repositoryTest", "src/test-config/repository-xml.xml", "target/repository"); - isInit = true; - } - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - public void tearDown() throws Exception - { - super.tearDown(); - } - - public static Test suite() - { - // All methods starting with "test" will be executed in the test suite. - return new TestSuite(RepositoryUtilTest.class); - } - - /** - * Test for getRepository() and login - * - */ - public void testgetRegistryAndLogin() - { - try - { - Repository repository = RepositoryUtil.getRepository("repositoryTest"); - assertNotNull("The repository is null", repository); - Session session = RepositoryUtil.login(repository, "superuser", "superuser"); - Node root = session.getRootNode(); - assertNotNull("Root node is null", root); - session.logout(); - } - catch (Exception e) - { - e.printStackTrace(); - fail("Unable to find the repository : " + e); - } - - } - - /** - * Simple unit test to check if custome node types are well defined - * - */ - public void testgetCustomNodeType() - { - try - { - Repository repository = RepositoryUtil.getRepository("repositoryTest"); - Session session = RepositoryUtil.login(repository, "superuser", "superuser"); - NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager(); - - // TODO custom node types not implemented yet - - //NodeType nodeType = nodeTypeManager.getNodeType("graffito:folder"); - //assertNotNull("Root node is null", nodeType); - - session.logout(); - } - catch (Exception e) - { - e.printStackTrace(); - fail("Unable to find the repository : " + e); - } - } - - /** - * Test for getParentPath() - * - */ - public void testgetParentPath() - { - try - { - String parentPath = RepositoryUtil.getParentPath("/test"); - assertNotNull("parent path is null for /test", parentPath); - assertTrue("parent path is incorrect for /test", parentPath.equals("/")); - - parentPath = RepositoryUtil.getParentPath("/test/test2"); - assertNotNull("parent path is null for /test/test2", parentPath); - assertTrue("parent path is incorrect for /test/test2", parentPath.equals("/test")); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Unable to find the repository : " + e); - } - } - - /** - * Test for getNodeName() - * - */ - public void testgetNodeName() - { - try - { - String nodeName = RepositoryUtil.getNodeName("/test"); - assertNotNull("node name is null for /test", nodeName); - assertTrue("node name is incorrect for /test", nodeName.equals("test")); - - nodeName = RepositoryUtil.getNodeName("/test/test2"); - assertNotNull("node name is null for /test/test2", nodeName); - assertTrue("node name is incorrect for /test/test2", nodeName.equals("test2")); - - } - catch (Exception e) - { - e.printStackTrace(); - fail("Unable to find the repository : " + e); - } - } - - public void testEncodePath() - { - String encodedPath = RepositoryUtil.encodePath("/files/test/1.0"); - assertTrue("Incorrect encoded path", encodedPath.equals("/files/test/_x0031_.0")); - - encodedPath = RepositoryUtil.encodePath("/files/test/12aa/b/34/rrr/1.0"); - assertTrue("Incorrect encoded path", encodedPath.equals("/files/test/_x0031_2aa/b/_x0033_4/rrr/_x0031_.0")); - - } - - public void testUserTransaction() - { - try - { - Repository repository = RepositoryUtil.getRepository("repositoryTest"); - assertNotNull("The repository is null", repository); - Session session = RepositoryUtil.login(repository, "superuser", - "superuser"); - - UserTransaction utx = new UserTransactionImpl(session); - - // start transaction - utx.begin(); - - // add node and save - Node root = session.getRootNode(); - Node n = root.addNode("test"); - root.save(); - utx.commit(); - - assertTrue("test node doesn't exist", session.itemExists("/test")); - - utx = new UserTransactionImpl(session); - utx.begin(); - Node test = (Node) session.getItem("/test"); - test.remove(); - session.save(); - utx.rollback(); - - assertTrue("test node doesn't exist", session.itemExists("/test")); - - utx = new UserTransactionImpl(session); - utx.begin(); - test = (Node) session.getItem("/test"); - test.remove(); - session.save(); - utx.commit(); - - assertFalse("test node exists", session.itemExists("/test")); - - } - catch (Exception e) - { - - } - } - -} \ No newline at end of file diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/CmsObject.java b/src/test/org/apache/portals/graffito/jcr/testmodel/CmsObject.java deleted file mode 100644 index 53574203..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/CmsObject.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - - -/** - * CmsObject test - * - * @author Christophe Lombart - * - * - */ -public class CmsObject -{ - public static final long serialVersionUID = 1; - - protected Long objectId; - - protected Long parentId; //parent folder id - protected Folder parentFolder; - - protected String name; - - protected String description; - protected String title; - protected Date creationDate; - protected Date lastModified; - - /** - * Special attribute telling OJB the object's concrete type. - * - */ - protected String ojbConcreteClass; - - /** - * Constructor - */ - public CmsObject() - { - ojbConcreteClass = this.getClass().getName(); - } - - - - /** - * @return Returns the parentFolder. - */ - public Folder getParentFolder() - { - return parentFolder; - } - - /** - * @param parentFolder The parentFolder to set. - */ - public void setParentFolder(Folder parentFolder) - { - this.parentFolder = parentFolder; - } - - /** - * @param parentId The parentId to set. - */ - public void setParentId(Long parentId) - { - this.parentId = parentId; - } - - /** - * @return Returns the parentId. - */ - public Long getParentId() - { - return parentId; - } - - - /** - * @return Returns the objectId. - */ - public Long getObjectId() - { - return objectId; - } - - /** - * @param objectId The objectId to set. - */ - public void setObjectId(Long objectId) - { - this.objectId = objectId; - } - - - /* - * @see org.apache.portals.graffito.model.CmsObject#getName() - */ - public String getName() - { - return this.name; - } - - /* - * @see org.apache.portals.graffito.model.CmsObject#setName(java.lang.String) - */ - public void setName(String name) - { - this.name = name; - } - - - /* - * @see org.apache.portals.graffito.model.CmsObject#getCreationDate() - */ - public Date getCreationDate() - { - return this.creationDate; - } - - /* - * @see org.apache.portals.graffito.model.CmsObject#setCreationDate(java.util.Date) - */ - public void setCreationDate(Date creationDate) - { - this.creationDate = creationDate; - } - - /* - * @see org.apache.portals.graffito.model.CmsObject#getLastModified() - */ - public Date getLastModified() - { - return this.lastModified; - } - - /* - * @see org.apache.portals.graffito.model.CmsObject#setLastModified(java.util.Date) - */ - public void setLastModified(Date lastModified) - { - this.lastModified = lastModified; - } - - /* - * @see org.apache.portals.graffito.model.CmsObject#getDescription() - */ - public String getDescription() - { - return this.description; - } - - /* - * @see org.apache.portals.graffito.model.CmsObject#setDescription(java.lang.String) - */ - public void setDescription(String v) - { - this.description = v; - } - - /** - * @see org.apache.portals.graffito.model.CmsObject#getTitle() - */ - public String getTitle() - { - return this.title; - } - - /** - * @see org.apache.portals.graffito.model.CmsObject#setTitle(java.lang.String) - */ - public void setTitle(String title) - { - this.title = title; - } - - - - - -} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/Content.java b/src/test/org/apache/portals/graffito/jcr/testmodel/Content.java deleted file mode 100644 index d4675e4a..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/Content.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import java.io.UnsupportedEncodingException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - - - -/** - * Content object - * - * @author Christophe Lombart - * - */ -public class Content -{ - protected final static Log log = LogFactory.getLog(Content.class); - - protected Long contentId; - - protected byte[] content; - - protected String encoding; - - - /** - * @return Returns the content. - */ - public InputStream getContentStream() - { - return new ByteArrayInputStream(content); - } - - /** - * @return Returns the content. - */ - public byte[] getContentByte() - { - - return content; - } - - - /** - * @param stream The content to set. - */ - public void setContent(byte[] stream) - { - - content = stream; - - } - - /** - * @return Returns the encoding. - */ - public String getEncoding() - { - return encoding; - } - - /** - * @param encoding The encoding to set. - */ - public void setEncoding(String encoding) - { - this.encoding = encoding; - } -} - - diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/Document.java b/src/test/org/apache/portals/graffito/jcr/testmodel/Document.java deleted file mode 100644 index 29000fd3..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/Document.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - - -import java.util.*; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * CMS VersionnedDocument implementation. - * - * @author Christophe Lombart - * - */ -public class Document extends CmsObject -{ - protected final static Log log = LogFactory.getLog(Document.class); - - protected long size; - protected String contentType; - - protected Content content; - - - /** - * @see org.apache.portals.graffito.model.Document#getContentType() - */ - public String getContentType() - { - return this.contentType; - } - - /** - * @see org.apache.portals.graffito.model.Document#setContentType(java.lang.String) - */ - public void setContentType(String contentType) - { - this.contentType = contentType; - } - - - /** - * - * @see org.apache.portals.graffito.model.Document#getSize() - */ - public long getSize() - { - return size; - } - - /** - * - * @see org.apache.portals.graffito.model.Document#setSize(long) - */ - public void setSize(long size) - { - this.size = size; - } - - - public Content getContent() - { - return content; - } - public void setContent(Content content) - { - this.content = content; - } -} - diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/File.java b/src/test/org/apache/portals/graffito/jcr/testmodel/File.java deleted file mode 100755 index f89bf4e7..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/File.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.apache.portals.graffito.jcr.testmodel; - -import java.io.InputStream; -import java.util.Calendar; - -public class File -{ - - private String mimeType; - private String encoding; - private InputStream data; - private Calendar lastModified; - - public InputStream getData() - { - return data; - } - public void setData(InputStream data) - { - this.data = data; - } - public String getEncoding() - { - return encoding; - } - public void setEncoding(String encoding) - { - this.encoding = encoding; - } - public Calendar getLastModified() - { - return lastModified; - } - public void setLastModified(Calendar lastModified) - { - this.lastModified = lastModified; - } - public String getMimeType() - { - return mimeType; - } - public void setMimeType(String mimeType) - { - this.mimeType = mimeType; - } - - -} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/Folder.java b/src/test/org/apache/portals/graffito/jcr/testmodel/Folder.java deleted file mode 100644 index c25a3fe1..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/Folder.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -import java.util.List; - - - - -/** - * CMS Folder Test - * - * @author Christophe Lombart - * @version $Id: Folder.java,v 1.1 2004/12/22 20:36:59 christophe Exp $ - */ -public class Folder extends CmsObject -{ - - protected List folders; - protected List documents; - - /** - * @see org.apache.portals.graffito.model.Folder#getDocuments() - */ - public List getDocuments() - { - return documents; - } - - /** - * @see org.apache.portals.graffito.model.Folder#getFolders() - */ - public List getFolders() - { - return folders; - } - -} - diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/MultiValue.java b/src/test/org/apache/portals/graffito/jcr/testmodel/MultiValue.java deleted file mode 100644 index ea4ed543..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/MultiValue.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel; - -import java.util.Collection; - -/** - * - * Simple object used to test multivalue properties - * - * @author Lombart - * Christophe - * @version $Id: Exp $ - */ -public class MultiValue -{ - private String path; - - private String name; - - private Collection multiValues; - - private Collection nullMultiValues; - - - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } - - /** - * @param name The name to set. - */ - public void setName(String name) - { - this.name = name; - } - - /** - * @return Returns the multiValues. - */ - public Collection getMultiValues() - { - return multiValues; - } - - /** - * @param multiValues - * The multiValues to set. - */ - public void setMultiValues(Collection multiValues) - { - this.multiValues = multiValues; - } - - /** - * @return Returns the nullMultiValues. - */ - public Collection getNullMultiValues() - { - return nullMultiValues; - } - - /** - * @param nullMultiValues - * The nullMultiValues to set. - */ - public void setNullMultiValues(Collection nullMultiValues) - { - this.nullMultiValues = nullMultiValues; - } - -} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/Page.java b/src/test/org/apache/portals/graffito/jcr/testmodel/Page.java deleted file mode 100755 index 9b7ff24f..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/Page.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.testmodel; - -import java.util.ArrayList; -import java.util.Collection; - -/** - * - * @author Christophe Lombart - * - */ -public class Page -{ - String path; - String title; - Collection paragraphs; - - public String getPath() - { - return path; - } - public void setPath(String path) - { - this.path = path; - } - /** - * @return Returns the paragraphs. - */ - public Collection getParagraphs() - { - return paragraphs; - } - /** - * @param paragraphs The paragraphs to set. - */ - public void setParagraphs(Collection paragraphs) - { - this.paragraphs = paragraphs; - } - /** - * @return Returns the title. - */ - public String getTitle() - { - return title; - } - /** - * @param title The title to set. - */ - public void setTitle(String title) - { - this.title = title; - } - - public void addParagraph(Paragraph paragraph) - { - if (paragraphs == null) - { - paragraphs = new ArrayList(); - } - - paragraphs.add(paragraph); - } - - - -} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/Paragraph.java b/src/test/org/apache/portals/graffito/jcr/testmodel/Paragraph.java deleted file mode 100755 index 41655307..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/Paragraph.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.testmodel; - -/** - * - * @author Christophe Lombart - * - */ -public class Paragraph -{ - private String path; - private String text; - - - - public String getPath() - { - return path; - } - - public void setPath(String path) - { - this.path = path; - } - - public Paragraph() - { - this.text = "Default text"; - } - - public Paragraph(String text) - { - this.text = text; - } - - /** - * @return Returns the text. - */ - public String getText() - { - return text; - } - - /** - * @param text The text to set. - */ - public void setText(String text) - { - this.text = text; - } - -} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/HashMapElement.java b/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/HashMapElement.java deleted file mode 100755 index 5e3bcf7d..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/HashMapElement.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2000-2005 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.portals.graffito.jcr.testmodel.hashmap; - -import java.util.HashMap; -import java.util.Iterator; - -import org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection; - -/** - * - * @author Christophe Lombart - * - */ -public class HashMapElement extends HashMap implements ManageableCollection -{ - - /** - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#addObject(java.lang.Object) - */ - public void addObject(Object object) - { - if (object instanceof Element) - { - this.put(((Element)object).getId(), object); - } - } - - /** - * @see org.apache.portals.graffito.jcr.persistence.collectionconverter.ManageableCollection#getIterator() - */ - public Iterator getIterator() - { - return this.values().iterator(); - } - - public int getSize() - { - - return this.size(); - } - - -} diff --git a/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/Main.java b/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/Main.java deleted file mode 100755 index b01a5a11..00000000 --- a/src/test/org/apache/portals/graffito/jcr/testmodel/hashmap/Main.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2000-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.portals.graffito.jcr.testmodel.hashmap; - -import java.util.HashMap; - -/** - * - * @author Lombart Christophe - * @version $Id: Exp $ - */ -public class Main -{ - private String path; - private String text; - private HashMapElement elements; - - - - public String getPath() { - return path; - } - public void setPath(String path) { - this.path = path; - } - /** - * @return Returns the elements. - */ - public HashMapElement getElements() - { - return elements; - } - /** - * @param elements The elements to set. - */ - public void setElements(HashMapElement elements) - { - this.elements = elements; - } - /** - * @return Returns the text. - */ - public String getText() - { - return text; - } - /** - * @param text The text to set. - */ - public void setText(String text) - { - this.text = text; - } - - -} diff --git a/src/test/repository/repository.xml b/src/test/repository/repository.xml new file mode 100644 index 00000000..d73ed46c --- /dev/null +++ b/src/test/repository/repository.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/resources/log4j.properties b/src/test/resources/log4j.properties new file mode 100644 index 00000000..df4fee27 --- /dev/null +++ b/src/test/resources/log4j.properties @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +log4j.rootLogger=INFO, file + +# 'file' is set to be a FileAppender. +log4j.appender.file=org.apache.log4j.FileAppender +log4j.appender.file.File=target/test-output.log + +# 'file' uses PatternLayout. +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss} *%-5p* [%t] %c{1}: %m (%F, line %L)\n diff --git a/src/test/resources/repositoryHelperPool.properties b/src/test/resources/repositoryHelperPool.properties new file mode 100644 index 00000000..f7497fef --- /dev/null +++ b/src/test/resources/repositoryHelperPool.properties @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# first helper uses default values +helper.0.= diff --git a/src/test/resources/repositoryStubImpl.properties b/src/test/resources/repositoryStubImpl.properties new file mode 100644 index 00000000..5503b4bf --- /dev/null +++ b/src/test/resources/repositoryStubImpl.properties @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Stub implementation class +javax.jcr.tck.repository_stub_impl=org.apache.jackrabbit.core.JackrabbitRepositoryStub diff --git a/src/test/test-config/jcrmapping-Enum.xml b/src/test/test-config/jcrmapping-Enum.xml new file mode 100644 index 00000000..1cf00b32 --- /dev/null +++ b/src/test/test-config/jcrmapping-Enum.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-atomic.xml b/src/test/test-config/jcrmapping-atomic.xml new file mode 100644 index 00000000..0b5f892c --- /dev/null +++ b/src/test/test-config/jcrmapping-atomic.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-auto.xml b/src/test/test-config/jcrmapping-auto.xml new file mode 100644 index 00000000..f65090ca --- /dev/null +++ b/src/test/test-config/jcrmapping-auto.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-avoidrecursiveloop.xml b/src/test/test-config/jcrmapping-avoidrecursiveloop.xml new file mode 100644 index 00000000..7bfa6101 --- /dev/null +++ b/src/test/test-config/jcrmapping-avoidrecursiveloop.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-beandescriptor.xml b/src/test/test-config/jcrmapping-beandescriptor.xml new file mode 100644 index 00000000..eabbdd15 --- /dev/null +++ b/src/test/test-config/jcrmapping-beandescriptor.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-complex-collections.xml b/src/test/test-config/jcrmapping-complex-collections.xml new file mode 100644 index 00000000..2b5788fd --- /dev/null +++ b/src/test/test-config/jcrmapping-complex-collections.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-default.xml b/src/test/test-config/jcrmapping-default.xml new file mode 100644 index 00000000..7e9b99b9 --- /dev/null +++ b/src/test/test-config/jcrmapping-default.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-inheritance.xml b/src/test/test-config/jcrmapping-inheritance.xml new file mode 100644 index 00000000..1f7d5757 --- /dev/null +++ b/src/test/test-config/jcrmapping-inheritance.xml @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-jcrnodetypes.xml b/src/test/test-config/jcrmapping-jcrnodetypes.xml new file mode 100644 index 00000000..9dee28b5 --- /dev/null +++ b/src/test/test-config/jcrmapping-jcrnodetypes.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-proxy.xml b/src/test/test-config/jcrmapping-proxy.xml new file mode 100644 index 00000000..77ac6deb --- /dev/null +++ b/src/test/test-config/jcrmapping-proxy.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-sibling.xml b/src/test/test-config/jcrmapping-sibling.xml new file mode 100644 index 00000000..e577a014 --- /dev/null +++ b/src/test/test-config/jcrmapping-sibling.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-testdigester.xml b/src/test/test-config/jcrmapping-testdigester.xml new file mode 100644 index 00000000..79a150cd --- /dev/null +++ b/src/test/test-config/jcrmapping-testdigester.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping-uuid.xml b/src/test/test-config/jcrmapping-uuid.xml new file mode 100644 index 00000000..ee3008a9 --- /dev/null +++ b/src/test/test-config/jcrmapping-uuid.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/jcrmapping.xml b/src/test/test-config/jcrmapping.xml new file mode 100644 index 00000000..5155b7f4 --- /dev/null +++ b/src/test/test-config/jcrmapping.xml @@ -0,0 +1,152 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-config/nodetypes/custom_nodetypes.xml b/src/test/test-config/nodetypes/custom_nodetypes.xml new file mode 100644 index 00000000..02cdbc1a --- /dev/null +++ b/src/test/test-config/nodetypes/custom_nodetypes.xml @@ -0,0 +1,265 @@ + + + + + + + nt:base + + + + + + + mix:lockable + nt:base + + + + + + + + mix:versionable + nt:base + + + + + + + + mix:versionable + nt:base + + + + + + + mix:versionable + nt:base + + + + + ocm:paragraph + + + + + + + mix:versionable + nt:base + + + + + ocm:paragraph + + + + + + + mix:versionable + nt:base + + + + + + + + nt:base + + + + + + + + ocm:cmsobjectimpl + + + + + + mix:versionable + nt:base + + + + + + + + + ocm:contentimpl + + + + + + ocm:documentstream + + + + + + + ocm:documentimpl + + + + + + + ocm:cmsobjectimpl + + + + ocm:cmsobjectimpl + + + + + + + mix:versionable + nt:base + + + + + + + nt:base + + + + + + ocm:cmsobject + + + + + + ocm:cmsobject + + + + + + ocm:content + + + + + + + nt:base + + + + + abc + def + ghi + + + + + autoCreatePropValue + + + + + ccc + + + bbb + ccc + ddd + + + + + + + xx + yy + + + + + protectedValue + + + + + + + nt:base + + + + + + + + nt:base + + + + ocm:ntdetail + + + + + + + + + + p5DefaultValue + + + + + + + nt:base + ocm:DefTestMixin + + + + + + + p4DefaultValue + + + + + + diff --git a/src/test/test-config/nodetypes/nodetypes_test1.xml b/src/test/test-config/nodetypes/nodetypes_test1.xml new file mode 100644 index 00000000..2968de86 --- /dev/null +++ b/src/test/test-config/nodetypes/nodetypes_test1.xml @@ -0,0 +1,32 @@ + + + + + + + nt:base + + + + + diff --git a/xdocs/advanced-strategies.xml b/xdocs/advanced-strategies.xml deleted file mode 100644 index 56a76f71..00000000 --- a/xdocs/advanced-strategies.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - Christophe Lombart - Advanced Mapping Strategies - - - -
- - - - - - - - -

A component is an entity that cannot live by its own, but has a logical - meaning. Take for example an Address. It may live alone, but doesn't make much sense in some - systems. Once associated with an User it starts making sense. Now, as in RDBMS you can choose the - persist this as a record in a separate table with a 1-1 relation, or you may choose to persist - Address field along with the User. - - Now, returning to JCR, the component is fitting perfectly the mixin notion. A mixin cannot live by - its own in the repository. It is associated with some node. It's properties are added to the set of -original node. -

-
- - - -

Sometime, it should be interesting to map to a different jcr node structure. - Here is an example, for a class "File", we can have :

- - -

and in terms of JCR structure, we can have :

- - So, the jcr:content node is an extra node to specify in the mapping file. - -
- - - -
- -
diff --git a/xdocs/atomic-strategy.xml b/xdocs/atomic-strategy.xml deleted file mode 100644 index 92ff024c..00000000 --- a/xdocs/atomic-strategy.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - Christophe Lombart - Simple Object Mapping Strategies - - - -
- -

The field-descriptor maps a bean attribute into one JCR property. it can map any kind of atomic types (java primitive data types and their wrapper classes)

-

Based on our model defined here, the following field-descriptor is used to map the bean field "title" into the JCR property "graffito:title".

- - ]]> - -
- -

- [TO DO] -

-
- -

- [TO DO] -

-
- -
- -
diff --git a/xdocs/bean-strategy.xml b/xdocs/bean-strategy.xml deleted file mode 100644 index 3a07844e..00000000 --- a/xdocs/bean-strategy.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Christophe Lombart - Simple Object Mapping Strategies - - - -
- TODO - -
- -
diff --git a/xdocs/collection-strategy.xml b/xdocs/collection-strategy.xml deleted file mode 100644 index 3eed0838..00000000 --- a/xdocs/collection-strategy.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Christophe Lombart - Simple Object Mapping Strategies - - - -
- TODO -
- -
diff --git a/xdocs/engine-configuration.xml b/xdocs/engine-configuration.xml deleted file mode 100644 index ab784079..00000000 --- a/xdocs/engine-configuration.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Christophe Lombart - Graffito JCR Persistence Manager - - -
- -

TODO

-
- -
diff --git a/xdocs/engine-introduction.xml b/xdocs/engine-introduction.xml deleted file mode 100644 index e57fd1dc..00000000 --- a/xdocs/engine-introduction.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - Christophe Lombart - Graffito JCR Persistence Manager - - -
-

The main component in our framework is the Persistence manager. It converts an object graph into JCR nodes and properties and vice versa.

- -

ADD API overview here

-
- - - -

- Thanks to its XML descriptor file, the Persistence Manager can use the more appropriate mapping strategy for each object. - The descriptor file contains one class descriptor for each mapped class. Each class descriptor contains mapping information for the corresponding class attributes. The descriptor file contains also information on object associations, inheritance mapping strategy, lazy loading, cache strategy, ... -

-

- -

-

- There are 4 attributes/fields "types" : -

    -
  1. Simple fields : primitive data types and simple objects (String, Long, Double, ...) . Thoses fields are mapped into JCR properties.
  2. -
  3. Bean fields : One class can contain an 1..1 association to another bean. In this case, the attribute is a custom object. Those fields are mapped into JCR nodes.
  4. -
  5. Collection fields : One class can contain an 1..n association to a collection of beans (or Map). Those fields are mapped into a collection of JCR nodes.
  6. -
  7. Reference field : One good example to understand the "reference" type is the Folder concept. A folder "B" can have an attribute called "parentFolder" which is a simple field pointing to the parent folder "A" . Of course, in a JCR repository, it is a nonsense for persist this "parentFolder" attribute into a "B" subnode. Another interesting example are links made between cms objects (folders, documents, ...).
  8. -
-

-

- Of course, all those "mapping types" imply different mapping algorithms.See the "Mapping Strategies" section to get more information on the descriptor file. -

-
- -
- -
diff --git a/xdocs/engine-spring.xml b/xdocs/engine-spring.xml deleted file mode 100644 index bf4f186a..00000000 --- a/xdocs/engine-spring.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - Christophe Lombart - Graffito JCR Persistence Manager - - -
-

TO DO

-
- -
diff --git a/xdocs/graffito-jcr-mapping.dtd.txt b/xdocs/graffito-jcr-mapping.dtd.txt deleted file mode 100644 index 8cba6a42..00000000 --- a/xdocs/graffito-jcr-mapping.dtd.txt +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/xdocs/images/breadcrumbs.jpg b/xdocs/images/breadcrumbs.jpg deleted file mode 100755 index 1385fa0b..00000000 Binary files a/xdocs/images/breadcrumbs.jpg and /dev/null differ diff --git a/xdocs/images/collapsed.gif b/xdocs/images/collapsed.gif deleted file mode 100755 index f2509c9e..00000000 Binary files a/xdocs/images/collapsed.gif and /dev/null differ diff --git a/xdocs/images/expanded.gif b/xdocs/images/expanded.gif deleted file mode 100755 index 02b74626..00000000 Binary files a/xdocs/images/expanded.gif and /dev/null differ diff --git a/xdocs/images/external.png b/xdocs/images/external.png deleted file mode 100755 index 3f999fc8..00000000 Binary files a/xdocs/images/external.png and /dev/null differ diff --git a/xdocs/images/folder-open.gif b/xdocs/images/folder-open.gif deleted file mode 100755 index 3955d19e..00000000 Binary files a/xdocs/images/folder-open.gif and /dev/null differ diff --git a/xdocs/images/graffito.jpg b/xdocs/images/graffito.jpg deleted file mode 100755 index 04bfb208..00000000 Binary files a/xdocs/images/graffito.jpg and /dev/null differ diff --git a/xdocs/images/h3.jpg b/xdocs/images/h3.jpg deleted file mode 100755 index 57700f3d..00000000 Binary files a/xdocs/images/h3.jpg and /dev/null differ diff --git a/xdocs/images/h5.jpg b/xdocs/images/h5.jpg deleted file mode 100755 index 0d5d2e94..00000000 Binary files a/xdocs/images/h5.jpg and /dev/null differ diff --git a/xdocs/images/newwindow.png b/xdocs/images/newwindow.png deleted file mode 100755 index 6287f72b..00000000 Binary files a/xdocs/images/newwindow.png and /dev/null differ diff --git a/xdocs/images/pdf.gif b/xdocs/images/pdf.gif deleted file mode 100755 index 7bce3389..00000000 Binary files a/xdocs/images/pdf.gif and /dev/null differ diff --git a/xdocs/images/sample-model-doc.png b/xdocs/images/sample-model-doc.png deleted file mode 100644 index a3adace5..00000000 Binary files a/xdocs/images/sample-model-doc.png and /dev/null differ diff --git a/xdocs/index.xml b/xdocs/index.xml deleted file mode 100644 index 54733307..00000000 --- a/xdocs/index.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - Christophe Lombart - Graffito JCR Mapping - - -
- -

This Graffito subproject is an object/JCR persistence and query service. This tools lets you to persist java objects into a JCR compliant repository - including association, inheritance, polymorphism, composition, and the Java collections framework. Furthermore, this jcr-mapping allows you to express queries in Java-based Criteria, as well as in JCR query language.

- -

In order to easily support the JCR specification, any content application managing an high level object model can use this framework. For example, a classic Forum application contains objets like "Forum", "Topic" and "Post". Now these data objects (pojo) can be managed by our JCR mapping tools in order to persist them into a JCR compliant repository.

- - -
- -

- Sometimes it is very convenient to be able to just access the JCR nodes and properties directly from your presentation-layer for very simple things (mostly generic display). When a lot of "business logic" are involved, the JCR API can be too low level and real business objects (pojo) are more appreciate in a such case. -

- -
- -

- Before using this JCR framework, you should review the JCR specication and implementation like JackRabbit. -

- -
- -

There are no releases yet. See the menu 'Build a new application" for instructions on how to download and build the Graffito JCR mapping sources.

-
-
- -
diff --git a/xdocs/introduction-strategies.xml b/xdocs/introduction-strategies.xml deleted file mode 100644 index de98ed5e..00000000 --- a/xdocs/introduction-strategies.xml +++ /dev/null @@ -1,182 +0,0 @@ - - - - - Christophe Lombart - Introduction to the Mapping Strategies - - -
- -

- We are calling "Mapping strategies" the algorithm used to map bean fields into JCR nodes and/or properties. - -

- -

- In order to explain the basic mapping strategies, we will use the following simple object model : -

    -
  • A page contains a path (of course), a pageInfo and a collection of paragraphs.
  • -
  • The PageInfo class contains the title and the page description. We are using the pageInfo here to see all mapping features (see the bean-descriptors). In real application, this class is not necessary :-)
  • -
  • Each paragraph contains a path and a text field.
  • -
-

-

-

- This object model could be too simple for real applications and it is uses here just to simplify the description of the different mapping strategies. -

-

Based on that object model, we can define the following java classes :

- - -public class Page -{ - String path; - PageInfo pageInfo; - Collection paragraphs; - - /* Add here the getter and setter methods */ - - public void addParagraph(Paragraph paragraph) - { - if (paragraphs == null) - { - paragraphs = new ArrayList(); - } - - paragraphs.add(paragraph); - } -} - -public class PageInfo -{ - String path; - String title; - String description; - - /* Add here the getter and setter methods */ - -} - -public class Paragraph -{ - private String path; - private String text; - - /* Add here the getter and setter methods */ - -} - - - -

- ... and the class-descriptors can be : -

- - - - - - - - - - - - - - - - - - ]]> - -

- We will explain in more details each descriptors in the following sections (Mapping Atomic Fields,Mapping Bean Fields and Mapping Collection Fields. If the page is stored on the path "/mysite/mypage1" and contains 2 paragraphs, here is the resulting jcr structure : -

-

- -

-

It is possible to have another kind of jcr structure by using other mapping strategies. You can see the section "Advance Mapping strategies" to get more information on that.

- - - -

When you decide to map a bean class, you have to create a new class descriptor entry in the Persistence Manager descriptor file.

-

Here is a basic class descriptor example :

- - - - - ]]> - -

This class descriptor maps the class "org.apache.portals.graffito.jcr.testmodel.Paragraph" to the JCR type "nt:unstructured". Each field-descriptors maps one bean attribute to a JCR property. You can find more information on the field-descriptors in the page Mapping Atomic fields. -

-

- It is also possible to map a bean class to a specific JCR custom node type. The following class-descriptor map the class "org.apache.portals.graffito.jcr.testmodel.Paragraph" to the node type "graffito:paragraph". -

- - - - - ]]> - -

- In order to use correclty our example class with Jackrabbit, you should add the following node type definition in its custom_nodetypes.xml file or import the node type definition with the Jackrabbit API -

- - - - mix:versionable - nt:base - - - - - ]]> -

We are currently building a node type management tools which can import the node types from the class-descriptors.

-
- -

- Each mapped class contains a mandatory field called the "path field". It simply contains the JCR path associated to the object. - For example, the following descriptor specify the bean field "myPath" as the path field. -

- - ]]> - -
- -
- -
diff --git a/xdocs/navigation.xml b/xdocs/navigation.xml deleted file mode 100644 index e6ccaacc..00000000 --- a/xdocs/navigation.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/xdocs/stylesheets/maven-j2.css b/xdocs/stylesheets/maven-j2.css deleted file mode 100755 index f24af2f7..00000000 --- a/xdocs/stylesheets/maven-j2.css +++ /dev/null @@ -1,212 +0,0 @@ -/* ----------------------- -Theme Style ----------------------- -*/ -body { - background-color: #fff; - font-family: Verdana, Helvetica, Arial, sans-serif; - margin-left: auto; - margin-right: auto; - background-repeat: repeat-y; - font-size: 13px; - padding: 0px; -} - -td,select,input,li { - font-family: Verdana, Helvetica, Arial, sans-serif; - font-size: 12px; - color: #333333; -} - -code { - font-size: 12px; -} - -a { - text-decoration: none; -} - -a:link { - color: #47a; -} - -a:visited { - color: #666666; -} - -a:active,a:hover { - color: #990000; -} - -#legend li.externalLink { - background: url(../images/external.png) left top no-repeat; - padding-left: 18px; -} - -a.externalLink,a.externalLink:link,a.externalLink:visited,a.externalLink:active,a.externalLink:hover - { - background: url(../images/external.png) right center no-repeat; - padding-right: 18px; -} - -#legend li.newWindow { - background: url(../images/newwindow.png) left top no-repeat; - padding-left: 18px; -} - -a.newWindow,a.newWindow:link,a.newWindow:visited,a.newWindow:active,a.newWindow:hover - { - background: url(../images/newwindow.png) right center no-repeat; - padding-right: 18px; -} - -h2 { - font-size: 17px; - color: #333333; -} - -h3 { - padding: 4px 4px 4px 24px; - color: #666; - background-color: #ccc; - font-weight: bold; - font-size: 14px; - background-image: url(../images/h3.jpg); - background-repeat: no-repeat; - background-position: left bottom; -} - -p { - line-height: 1.3em; - font-size: 12px; - color: #000; -} - -#breadcrumbs { - height: 6px; - background-image: url(../images/breadcrumbs.jpg); - padding: 5px 10px 14px 20px; -} - -* html #breadcrumbs { - padding-bottom: 8px; -} - -#leftColumn { - margin: 10px 0 10px 0; - border-top-color: #ccc; - border-top-style: solid; - border-top-width: 1px; - border-right-color: #ccc; - border-right-style: solid; - border-right-width: 1px; - border-bottom-color: #ccc; - border-bottom-style: solid; - border-bottom-width: 1px; - padding-right: 5px; - padding-left: 5px; -} - -#navcolumn h5 { - font-size: smaller; - border-bottom: 1px solid #aaaaaa; - padding-top: 2px; - padding-left: 9px; - color: #49635a; - background-image: url(../images/h5.jpg); - background-repeat: no-repeat; - background-position: left bottom; -} - -table.bodyTable th { - color: white; - background-color: #bbb; - text-align: left; - font-weight: bold; -} - -table.bodyTable th,table.bodyTable td { - font-size: 11px; -} - -table.bodyTable tr.a { - background-color: #ddd; -} - -table.bodyTable tr.b { - background-color: #eee; -} - -.source { - border: 1px solid #999; - overflow: auto -} - -dt { - padding: 4px 4px 4px 24px; - color: #333333; - background-color: #ccc; - font-weight: bold; - font-size: 14px; - background-image: url(../images/h3.jpg); - background-repeat: no-repeat; - background-position: left bottom; -} - -.subsectionTitle { - font-size: 13px; - font-weight: bold; - color: #666; -} - -table { - font-size: 10px; -} - -.xright a:link,.xright a:visited,.xright a:active { - color: #666; -} - -.xright a:hover { - color: #003300; -} - -#banner { - height: 93px; - background: url(../images/banner.jpg); -} - -#navcolumn ul { - margin: 5px 0 15px -0em; -} - -#navcolumn ul a { - color: #333333; -} - -#navcolumn ul a:hover { - color: red; -} - -#intro { - border: solid #ccc 1px; - margin: 6px 0px 0px 0px; - padding: 10px 40px 10px 40px; -} - -.subsection { - margin-left: 3px; - color: #333333; -} - -.subsection p { - font-size: 12px; -} - -#footer { - padding: 10px; - margin: 20px 0px 20px 0px; - border-top: solid #ccc 1px; - color: #333333; -} \ No newline at end of file