diff options
Diffstat (limited to 'sca-java-1.x/branches/sca-java-1.0/modules/databinding')
117 files changed, 13627 insertions, 0 deletions
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.checkstyle b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.checkstyle new file mode 100644 index 0000000000..c7b30ffd5e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.checkstyle @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+
+<fileset-config file-format-version="1.2.0" simple-config="true">
+ <fileset name="all" enabled="true" check-config-name="Tuscany Checks" local="false">
+ <file-match-pattern match-pattern="." include-pattern="true"/>
+ </fileset>
+</fileset-config>
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.pmd b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.pmd new file mode 100644 index 0000000000..2db10d6a6a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.pmd @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+<pmd><useProjectRuleSet>true</useProjectRuleSet><rules/><includeDerivedFiles>false</includeDerivedFiles></pmd>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.ruleset b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.ruleset new file mode 100644 index 0000000000..ba9b5ce886 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/.ruleset @@ -0,0 +1,190 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<ruleset name="pmd-eclipse"> + <description>PMD Plugin preferences rule set</description> + + + <rule ref="rulesets/basic.xml/BooleanInstantiation"/> + <rule ref="rulesets/basic.xml/CollapsibleIfStatements"/> + <rule ref="rulesets/basic.xml/DoubleCheckedLocking"/> +<!--<rule ref="rulesets/basic.xml/EmptyCatchBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyFinallyBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyIfStmt"/>--> + <rule ref="rulesets/basic.xml/EmptyStatementNotInLoop"/> +<!--<rule ref="rulesets/basic.xml/EmptyStaticInitializer"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySwitchStatements"/>--> +<!--<rule ref="rulesets/basic.xml/EmptySynchronizedBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyTryBlock"/>--> +<!--<rule ref="rulesets/basic.xml/EmptyWhileStmt"/>--> + <rule ref="rulesets/basic.xml/ForLoopShouldBeWhileLoop"/> + <rule ref="rulesets/basic.xml/JumbledIncrementer"/> +<!--<rule ref="rulesets/basic.xml/OverrideBothEqualsAndHashcode"/>--> + <rule ref="rulesets/basic.xml/ReturnFromFinallyBlock"/> + <rule ref="rulesets/basic.xml/UnconditionalIfStatement"/> + <rule ref="rulesets/basic.xml/UnnecessaryConversionTemporary"/> + <rule ref="rulesets/basic.xml/UnnecessaryFinalModifier"/> + <rule ref="rulesets/basic.xml/UnnecessaryReturn"/> +<!--<rule ref="rulesets/basic.xml/UselessOverridingMethod"/>--> + +<!--<rule ref="rulesets/braces.xml/ForLoopsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfElseStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/IfStmtsMustUseBraces"/>--> +<!--<rule ref="rulesets/braces.xml/WhileLoopsMustUseBraces"/>--> + +<!--<rule ref="rulesets/clone.xml/CloneMethodMustImplementCloneable"/>--> +<!--<rule ref="rulesets/clone.xml/CloneThrowsCloneNotSupportedException"/>--> +<!--<rule ref="rulesets/clone.xml/ProperCloneImplementation"/>--> + +<!--<rule ref="rulesets/codesize.xml/CyclomaticComplexity"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveClassLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveMethodLength"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessiveParameterList"/>--> +<!--<rule ref="rulesets/codesize.xml/ExcessivePublicCount"/>--> +<!--<rule ref="rulesets/codesize.xml/TooManyFields"/>--> + +<rule ref="rulesets/controversial.xml/AssignmentInOperand"/> +<!--<rule ref="rulesets/controversial.xml/AtLeastOneConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/CallSuperInConstructor"/>--> +<!--<rule ref="rulesets/controversial.xml/DontImportSun"/>--> +<!--<rule ref="rulesets/controversial.xml/NullAssignment"/>--> +<!--<rule ref="rulesets/controversial.xml/OnlyOneReturn"/>--> +<!--<rule ref="rulesets/controversial.xml/SingularField"/>--> +<!--<rule ref="rulesets/controversial.xml/SuspiciousOctalEscape"/>--> +<!--<rule ref="rulesets/controversial.xml/UnnecessaryConstructor"/>--> +<rule ref="rulesets/controversial.xml/UnnecessaryParentheses"/> +<!--<rule ref="rulesets/controversial.xml/UnusedModifier"/>--> + +<!--<rule ref="rulesets/coupling.xml/CouplingBetweenObjects"/>--> +<!--<rule ref="rulesets/coupling.xml/ExcessiveImports"/>--> +<!--<rule ref="rulesets/coupling.xml/LooseCoupling"/>--> + +<!--<rule ref="rulesets/design.xml/AbstractClassWithoutAbstractMethod"/>--> +<!--<rule ref="rulesets/design.xml/AccessorClassGeneration"/>--> +<!--<rule ref="rulesets/design.xml/AssignmentToNonFinalStatic"/>--> +<!--<rule ref="rulesets/design.xml/AvoidDeeplyNestedIfStmts"/>--> +<!--<rule ref="rulesets/design.xml/AvoidInstanceofChecksInCatchClause"/>--> +<rule ref="rulesets/design.xml/AvoidProtectedFieldInFinalClass"/> +<!--<rule ref="rulesets/design.xml/AvoidReassigningParameters"/>--> +<!--<rule ref="rulesets/design.xml/AvoidSynchronizedAtMethodLevel"/>--> +<!--<rule ref="rulesets/design.xml/BadComparison"/>--> +<!--<rule ref="rulesets/design.xml/CloseConnection"/>--> +<!--<rule ref="rulesets/design.xml/CompareObjectsWithEquals"/>--> +<!--<rule ref="rulesets/design.xml/ConfusingTernary"/>--> +<rule ref="rulesets/design.xml/ConstructorCallsOverridableMethod"/> +<!--<rule ref="rulesets/design.xml/DefaultLabelNotLastInSwitchStmt"/>--> +<!--<rule ref="rulesets/design.xml/FinalFieldCouldBeStatic"/>--> +<rule ref="rulesets/design.xml/IdempotentOperations"/> +<!--<rule ref="rulesets/design.xml/ImmutableField"/>--> +<!--<rule ref="rulesets/design.xml/InstantiationToGetClass"/>--> +<!--<rule ref="rulesets/design.xml/MissingBreakInSwitch"/>--> +<!--<rule ref="rulesets/design.xml/MissingStaticMethodInNonInstantiatableClass"/>--> +<!--<rule ref="rulesets/design.xml/NonCaseLabelInSwitchStatement"/>--> +<!--<rule ref="rulesets/design.xml/NonStaticInitializer"/>--> +<rule ref="rulesets/design.xml/OptimizableToArrayCall"/> +<rule ref="rulesets/design.xml/PositionLiteralsFirstInComparisons"/> +<rule ref="rulesets/design.xml/SimplifyBooleanExpressions"/> +<rule ref="rulesets/design.xml/SimplifyBooleanReturns"/> +<rule ref="rulesets/design.xml/SimplifyConditional"/> +<!--<rule ref="rulesets/design.xml/SwitchDensity"/>--> +<!--<rule ref="rulesets/design.xml/SwitchStmtsShouldHaveDefault"/>--> +<!--<rule ref="rulesets/design.xml/UnnecessaryLocalBeforeReturn"/>--> +<!--<rule ref="rulesets/design.xml/UseLocaleWithCaseConversions"/>--> +<!--<rule ref="rulesets/design.xml/UseNotifyAllInsteadOfNotify"/>--> +<!--<rule ref="rulesets/design.xml/UseSingleton"/>--> + +<!--<rule ref="rulesets/finalizers.xml/EmptyFinalizer"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOnlyCallsSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeOverloaded"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeDoesNotCallSuperFinalize"/>--> +<!--<rule ref="rulesets/finalizers.xml/FinalizeShouldBeProtected"/>--> +<!--<rule ref="rulesets/finalizers.xml/AvoidCallingFinalize"/>--> + +<!--<rule ref="rulesets/imports.xml/DuplicateImports"/>--> +<!--<rule ref="rulesets/imports.xml/DontImportJavaLang"/>--> +<!--<rule ref="rulesets/imports.xml/UnusedImports"/>--> +<!--<rule ref="rulesets/imports.xml/ImportFromSamePackage"/>--> + +<!--<rule ref="rulesets/javabeans.xml/BeanMembersShouldSerialize"/>--> +<!--<rule ref="rulesets/javabeans.xml/MissingSerialVersionUID"/>--> + +<!--<rule ref="rulesets/junit.xml/JUnitStaticSuite"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitSpelling"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitAssertionsShouldIncludeMessage"/>--> +<!--<rule ref="rulesets/junit.xml/JUnitTestsShouldIncludeAssert"/>--> +<!--<rule ref="rulesets/junit.xml/TestClassWithoutTestCases"/>--> +<!--<rule ref="rulesets/junit.xml/UnnecessaryBooleanAssertion"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertEqualsInsteadOfAssertTrue"/>--> +<!--<rule ref="rulesets/junit.xml/UseAssertSameInsteadOfAssertTrue"/>--> + + <!--<rule ref="rulesets/logging-java.xml/AvoidPrintStackTrace"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/MoreThanOneLogger"/>--> + <!--<rule ref="rulesets/logging-java.xml/LoggerIsNotStaticFinal"/>--> + <!--<rule ref="rulesets/logging-java.xml/LogBlockWithoutIf"/>--> + <!--<rule ref="rulesets/logging-java.xml/SystemPrintln"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/UseCorrectExceptionLogging"/>--> + <!--<rule ref="rulesets/logging-jakarta-commons.xml/ProperLogger"/>--> + + <!--<rule ref="rulesets/naming.xml/ShortVariable"/>--> + <!--<rule ref="rulesets/naming.xml/LongVariable"/>--> + <!--<rule ref="rulesets/naming.xml/ShortMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/VariableNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/MethodNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/ClassNamingConventions"/>--> + <!--<rule ref="rulesets/naming.xml/AbstractNaming"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidDollarSigns"/>--> + <!--<rule ref="rulesets/naming.xml/MethodWithSameNameAsEnclosingClass"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousHashcodeMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/SuspiciousConstantFieldName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingTypeName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidFieldNameMatchingMethodName"/>--> + <!--<rule ref="rulesets/naming.xml/AvoidNonConstructorMethodsWithClassName"/>--> + <!--<rule ref="rulesets/naming.xml/NoPackage"/>--> + <!--<rule ref="rulesets/naming.xml/PackageCase"/>--> + + <!--<rule ref="rulesets/optimizations.xml/LocalVariableCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/MethodArgumentCouldBeFinal"/>--> + <!--<rule ref="rulesets/optimizations.xml/AvoidInstantiatingObjectsInLoops"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseArrayListInsteadOfVector"/>--> + <!--<rule ref="rulesets/optimizations.xml/SimplifyStartsWith"/>--> + <!--<rule ref="rulesets/optimizations.xml/UseStringBufferForStringAppends"/>--> + + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingThrowable"/>--> + <!--<rule ref="rulesets/strictexception.xml/SignatureDeclareThrowsException"/>--> + <!--<rule ref="rulesets/strictexception.xml/ExceptionAsFlowControl"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidCatchingNPE"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingRawExceptionTypes"/>--> + <!--<rule ref="rulesets/strictexception.xml/AvoidThrowingNullPointerException"/>--> + + <!--<rule ref="rulesets/strings.xml/AvoidDuplicateLiterals"/>--> + <!--<rule ref="rulesets/strings.xml/StringInstantiation"/>--> + <!--<rule ref="rulesets/strings.xml/StringToString"/>--> + <!--<rule ref="rulesets/strings.xml/AvoidConcatenatingNonLiteralsInStringBuffer"/>--> + <!--<rule ref="rulesets/strings.xml/UnnecessaryCaseChange"/>--> + + <!--<rule ref="rulesets/sunsecure.xml/MethodReturnsInternalArray"/>--> + <!--<rule ref="rulesets/sunsecure.xml/ArrayIsStoredDirectly"/>--> + + <rule ref="rulesets/unusedcode.xml/UnusedLocalVariable"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateField"/> + <rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod"/> + <!--<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter"/>--> + +</ruleset> diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/DISCLAIMER b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/DISCLAIMER new file mode 100644 index 0000000000..d68a410903 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/DISCLAIMER @@ -0,0 +1,8 @@ +Apache Tuscany is an effort undergoing incubation at The Apache Software
+Foundation (ASF), sponsored by the Apache Web Services PMC. Incubation is
+required of all newly accepted projects until a further review indicates that
+the infrastructure, communications, and decision making process have stabilized
+in a manner consistent with other successful ASF projects. While incubation
+status is not necessarily a reflection of the completeness or stability of the
+code, it does indicate that the project has yet to be fully endorsed by the ASF.
+
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/LICENSE b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/LICENSE @@ -0,0 +1,205 @@ + + 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/sca-java-1.x/branches/sca-java-1.0/modules/databinding/NOTICE b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/NOTICE new file mode 100644 index 0000000000..94481d6cfa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2007 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/pom.xml b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/pom.xml new file mode 100644 index 0000000000..bb18d2d3b9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/pom.xml @@ -0,0 +1,51 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-modules</artifactId> + <version>1.0-incubating-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + <artifactId>tuscany-databinding</artifactId> + <name>Apache Tuscany SCA DataBinding Framework</name> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-interface</artifactId> + <version>1.0-incubating-SNAPSHOT</version> + </dependency> + + <dependency> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + <version>1.0.1</version> + </dependency> + + <dependency> + <groupId>org.codehaus.woodstox</groupId> + <artifactId>wstx-asl</artifactId> + <version>3.2.1</version> + <scope>runtime</scope> + </dependency> + </dependencies> +</project> diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.java new file mode 100644 index 0000000000..34313fdae0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding; + +import java.lang.annotation.Annotation; + +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * DataBinding represents a data representation, for example, SDO, JAXB and AXIOM + */ +public interface DataBinding { + /** + * A special databinding for input message of an operation + */ + String IDL_INPUT = "idl:input"; + /** + * A special databinding for output message of an operation + */ + String IDL_OUTPUT = "idl:output"; + /** + * A special databinding for fault message of an operation + */ + String IDL_FAULT = "idl:fault"; + /** + * The name of a databinding should be case-insensitive and unique + * + * @return The name of the databinding + */ + String getName(); + + /** + * Get the aliases for the databinding + * + * @return An array of aliases + */ + String[] getAliases(); + + /** + * Introspect and populate information to a DataType model + * + * @param dataType The data type to be introspected + * @param annotations The java annotations + * @return true if the databinding has recognized the given data type + */ + boolean introspect(DataType dataType, Annotation[] annotations); + + /** + * Introspect the data to figure out the corresponding data type + * + * @param value The object to be checked + * @return The DataType or null if the java type is not supported by this databinding + */ + DataType introspect(Object value); + + /** + * Provide a WrapperHandler for this databinding + * @return A wrapper handler which can handle wrapping/wrapping for this databinding + */ + WrapperHandler getWrapperHandler(); + + /** + * Make a copy of the object for "pass-by-value" semantics + * @param source object to copy + * @return copy of the object passed in as argument + */ + Object copy(Object object); + + /** + * Get the type mapper for simple types + * @return The databinding-specific simple type mapper + */ + SimpleTypeMapper getSimpleTypeMapper(); + + /** + * Get the handler that can handle exceptions/faults in the + * databinding-specific way + * + * @return An instance of the exception handler + */ + ExceptionHandler getExceptionHandler(); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.java new file mode 100644 index 0000000000..205843e2be --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding; + +import java.lang.annotation.Annotation; + +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * An extension point for data binding extensions. + */ +public interface DataBindingExtensionPoint { + + /** + * Register a data binding + * + * @param dataBinding + */ + void addDataBinding(DataBinding dataBinding); + + /** + * Look up a data binding by id + * + * @param id The name of the databinding + * @return The databinding + */ + DataBinding getDataBinding(String id); + + /** + * Unregister a data binding + * + * @param id + * @return The unregistered databinding + */ + DataBinding removeDataBinding(String id); + + /** + * Introspect the java class to figure out what DataType supports it + * + * @param DataType The initial data type + * @param annotations The java annotations + * @return A DataType representing the java type or null if no databinding + * recognizes the java type + */ + boolean introspectType(DataType dataType, Annotation[] annotations); + + /** + * Introspect the java class to figure out what DataType supports it + * + * @param DataType The initial data type + * @param annotations The java annotations + * @param boolean Should be set to true if DataType parm represents an Exception + * @return A DataType representing the java type or null if no databinding + * recognizes the java type + */ + boolean introspectType(DataType dataType, Annotation[] annotations, boolean isFaultType); + + /** + * Introspect the value to figure out the corresponding DataType + * + * @param value The object value + * @return A DataType representing the value or null if no databinding + * recognizes the value + */ + DataType introspectType(Object value); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.java new file mode 100755 index 0000000000..69a0e4510a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.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.tuscany.sca.databinding; + +/** + * Data pipe allows a data source pushes data into its sink and pipe the data into its result + * + * @param <S> The data binding type of the sink + * @param <R> The data binding type of the result + */ +public interface DataPipe<S, R> { + + /** + * Returns a sink (for example, java.io.OutputStream, java.io.Writer or org.xml.sax.ContentHandler) to receive data + * pushed by the source + * + * @return The sink to consume data + */ + S getSink(); + + /** + * Returns the data populated by the sink + * + * @return + */ + R getResult(); + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.java new file mode 100644 index 0000000000..4486117d31 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding; + +/** + * Data pipe allows a data source pushes data into its sink and pipe the data into its result + * + */ +public interface DataPipeTransformer<S, R> extends Transformer { + + public DataPipe<S, R> newInstance(); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.java new file mode 100644 index 0000000000..1d167f463d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.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.tuscany.sca.databinding; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.ref.WeakReference; +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.databinding.impl.ServiceConfigurationUtil; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; + +/** + * The default implementation of a data binding extension point. + * + * @version $Rev$ $Date$ + */ +public class DefaultDataBindingExtensionPoint implements DataBindingExtensionPoint { + private final Map<String, DataBinding> bindings = new HashMap<String, DataBinding>(); + private static final Logger logger = Logger.getLogger(DefaultTransformerExtensionPoint.class.getName()); + private boolean loadedDataBindings; + + public DefaultDataBindingExtensionPoint() { + } + + public DataBinding getDataBinding(String id) { + if (id == null) { + return null; + } + DataBinding dataBinding = bindings.get(id.toLowerCase()); + if (dataBinding == null) { + loadDataBindings(); + dataBinding = bindings.get(id.toLowerCase()); + } + return dataBinding; + } + + public void addDataBinding(DataBinding dataBinding) { + if (logger.isLoggable(Level.FINE)) { + String className = dataBinding.getClass().getName(); + boolean lazy = false; + if (dataBinding instanceof LazyDataBinding) { + className = ((LazyDataBinding) dataBinding).className; + lazy = true; + } + logger.fine("Adding databinding: " + className + ";type=" + + dataBinding.getName() + ",lazy=" + lazy); + } + bindings.put(dataBinding.getName().toLowerCase(), dataBinding); + String[] aliases = dataBinding.getAliases(); + if (aliases != null) { + for (String alias : aliases) { + bindings.put(alias.toLowerCase(), dataBinding); + } + } + } + + public DataBinding removeDataBinding(String id) { + if (id == null) { + return null; + } + DataBinding dataBinding = bindings.remove(id.toLowerCase()); + if (dataBinding != null) { + String[] aliases = dataBinding.getAliases(); + if (aliases != null) { + for (String alias : aliases) { + bindings.remove(alias.toLowerCase()); + } + } + } + return dataBinding; + } + + /** + * Dynamically load data bindings declared under META-INF/services + */ + private void loadDataBindings() { + if (loadedDataBindings) + return; + + // Get the databinding service declarations + ClassLoader classLoader = DataBinding.class.getClassLoader(); + List<String> dataBindingDeclarations; + try { + dataBindingDeclarations = + ServiceConfigurationUtil.getServiceClassNames(classLoader, DataBinding.class.getName()); + } catch (IOException e) { + throw new IllegalStateException(e); + } + + // Load data bindings + for (String dataBindingDeclaration : dataBindingDeclarations) { + Map<String, String> attributes = ServiceConfigurationUtil.parseServiceDeclaration(dataBindingDeclaration); + String className = attributes.get("class"); + String type = attributes.get("type"); + String name = attributes.get("name"); + + // Create a data binding wrapper and register it + DataBinding dataBinding = new LazyDataBinding(type, name, classLoader, className); + addDataBinding(dataBinding); + } + + loadedDataBindings = true; + } + + /** + * A data binding facade allowing data bindings to be lazily loaded and + * initialized. + */ + private static class LazyDataBinding implements DataBinding { + + private String name; + private String[] aliases; + private WeakReference<ClassLoader> classLoader; + private String className; + private DataBinding dataBinding; + + private LazyDataBinding(String type, String name, ClassLoader classLoader, String className) { + this.name = type; + if (name != null) { + this.aliases = new String[] {name}; + } + this.classLoader = new WeakReference<ClassLoader>(classLoader); + this.className = className; + } + + /** + * Load and instantiate the data binding class. + * + * @return The data binding. + */ + @SuppressWarnings("unchecked") + private DataBinding getDataBinding() { + if (dataBinding == null) { + try { + Class<DataBinding> dataBindingClass = + (Class<DataBinding>)Class.forName(className, true, classLoader.get()); + Constructor<DataBinding> constructor = dataBindingClass.getConstructor(); + dataBinding = constructor.newInstance(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return dataBinding; + } + + public Object copy(Object object) { + return getDataBinding().copy(object); + } + + public String[] getAliases() { + return aliases; + } + + public ExceptionHandler getExceptionHandler() { + return getDataBinding().getExceptionHandler(); + } + + public String getName() { + return name; + } + + public SimpleTypeMapper getSimpleTypeMapper() { + return getDataBinding().getSimpleTypeMapper(); + } + + public WrapperHandler getWrapperHandler() { + return getDataBinding().getWrapperHandler(); + } + + public boolean introspect(DataType dataType, Annotation[] annotations) { + return getDataBinding().introspect(dataType, annotations); + } + + public DataType introspect(Object value) { + return getDataBinding().introspect(value); + } + } + + //FIXME The following methods should not be on the extension point + // they should be on a separate class + public boolean introspectType(DataType dataType, Annotation[] annotations) { + return introspectType(dataType, annotations, false); + } + + // + // Leverage the DataBinding ExceptionHandler to calculate the DataType of an exception DataType + // + public boolean introspectType(DataType dataType, Annotation[] annotations, boolean isException) { + loadDataBindings(); + for (DataBinding binding : bindings.values()) { + // don't introspect for JavaBeansDatabinding as all javatypes will + // anyways match to its basetype + // which is java.lang.Object. Default to this only if no databinding + // results + if (!binding.getName().equals(JavaBeansDataBinding.NAME)) { + if (isException) { + // Next look to see if the DB's exceptionHandler handles this exception + ExceptionHandler excHandler = binding.getExceptionHandler(); + if (excHandler != null) { + // Assymetric to have the introspect() methods set the DataBindings themselves + // whereas we're setting it ourselves here. + DataType faultType = excHandler.getFaultType(dataType); + if (faultType != null) { + dataType.setDataBinding(binding.getName()); + dataType.setLogical(faultType); + return true; + } + } + } else { + if (binding.introspect(dataType, annotations)) { + return true; + } + } + } + } + // FIXME: Should we honor the databinding from operation/interface + // level? + Class physical = dataType.getPhysical(); + if (physical == Object.class) { + return false; + } + dataType.setDataBinding(JavaBeansDataBinding.NAME); + return false; + } + + public DataType introspectType(Object value) { + loadDataBindings(); + DataType dataType = null; + for (DataBinding binding : bindings.values()) { + // don't introspect for JavaBeansDatabinding as all javatypes will + // anyways match to its basetype + // which is java.lang.Object. Default to this only if no databinding + // results + if (!binding.getName().equals(JavaBeansDataBinding.NAME)) { + dataType = binding.introspect(value); + } + if (dataType != null) { + return dataType; + } + } + return new DataTypeImpl<Class>(JavaBeansDataBinding.NAME, value.getClass(), value.getClass()); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java new file mode 100755 index 0000000000..bc58a4bf8b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java @@ -0,0 +1,278 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding; + +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.databinding.impl.DirectedGraph; +import org.apache.tuscany.sca.databinding.impl.ServiceConfigurationUtil; + +/** + * @version $Rev$ $Date$ + */ +public class DefaultTransformerExtensionPoint implements TransformerExtensionPoint { + private static final Logger logger = Logger.getLogger(DefaultTransformerExtensionPoint.class.getName()); + private boolean loadedTransformers; + + private final DirectedGraph<Object, Transformer> graph = new DirectedGraph<Object, Transformer>(); + + public DefaultTransformerExtensionPoint() { + } + + public void addTransformer(String sourceType, String resultType, int weight, Transformer transformer) { + if (logger.isLoggable(Level.FINE)) { + String className = transformer.getClass().getName(); + boolean lazy = false; + boolean pull = (transformer instanceof PullTransformer); + if (transformer instanceof LazyPullTransformer) { + className = ((LazyPullTransformer) transformer).className; + lazy = true; + } + if (transformer instanceof LazyPushTransformer) { + className = ((LazyPushTransformer) transformer).className; + lazy = true; + } + + logger.fine("Adding transformer: " + className + ";source=" + + sourceType + ",target=" + resultType + ",weight=" + + weight + ",type=" + (pull ? "pull" : "push") + ",lazy=" + + lazy); + } + graph.addEdge(sourceType, resultType, transformer, weight); + } + + public void addTransformer(Transformer transformer) { + addTransformer(transformer.getSourceDataBinding(), + transformer.getTargetDataBinding(), + transformer.getWeight(), + transformer); + } + + public boolean removeTransformer(String sourceType, String resultType) { + return graph.removeEdge(sourceType, resultType); + } + + public Transformer getTransformer(String sourceType, String resultType) { + loadTransformers(); + + DirectedGraph<Object, Transformer>.Edge edge = graph.getEdge(sourceType, resultType); + return (edge == null) ? null : edge.getValue(); + } + + /** + * Dynamically load transformers registered under META-INF/services. + * + */ + private void loadTransformers() { + if (loadedTransformers) { + return; + } + loadTransformers(PullTransformer.class); + loadTransformers(PushTransformer.class); + loadedTransformers = true; + } + + /** + * Dynamically load transformers registered under META-INF/services. + * + * @param transformerClass + */ + private void loadTransformers(Class<?> transformerClass) { + + // Get the transformer service declarations + ClassLoader classLoader = transformerClass.getClassLoader(); + List<String> transformerDeclarations; + try { + transformerDeclarations = ServiceConfigurationUtil.getServiceClassNames(classLoader, transformerClass.getName()); + } catch (IOException e) { + throw new IllegalStateException(e); + } + + // Load transformers + for (String transformerDeclaration: transformerDeclarations) { + Map<String, String> attributes = ServiceConfigurationUtil.parseServiceDeclaration(transformerDeclaration); + String className = attributes.get("class"); + String source = attributes.get("source"); + String target = attributes.get("target"); + int weight = Integer.valueOf(attributes.get("weight")); + + // Create a transformer wrapper and register it + Transformer transformer; + if (transformerClass == PullTransformer.class) { + transformer = new LazyPullTransformer(source, target, weight, classLoader, className); + } else { + transformer = new LazyPushTransformer(source, target, weight, classLoader, className); + } + addTransformer(transformer); + } + } + + /** + * A transformer facade allowing transformers to be lazily loaded + * and initialized. + */ + private static class LazyPullTransformer implements PullTransformer<Object, Object> { + + private String source; + private String target; + private int weight; + private WeakReference<ClassLoader> classLoader; + private String className; + private PullTransformer<Object, Object> transformer; + + public LazyPullTransformer(String source, String target, int weight, ClassLoader classLoader, String className) { + this.source = source; + this.target = target; + this.weight = weight; + this.classLoader = new WeakReference<ClassLoader>(classLoader); + this.className = className; + } + + /** + * Load and instantiate the transformer class. + * + * @return The transformer. + */ + @SuppressWarnings("unchecked") + private PullTransformer<Object, Object> getTransformer() { + if (transformer == null) { + try { + Class<PullTransformer<Object, Object>> transformerClass = + (Class<PullTransformer<Object, Object>>)Class.forName(className, true, classLoader.get()); + Constructor<PullTransformer<Object, Object>> constructor = transformerClass.getConstructor(); + transformer = constructor.newInstance(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return transformer; + } + + public String getSourceDataBinding() { + return source; + } + + public String getTargetDataBinding() { + return target; + } + + public int getWeight() { + return weight; + } + + public Object transform(Object source, TransformationContext context) { + return getTransformer().transform(source, context); + } + + } + + /** + * A transformer facade allowing transformers to be lazily loaded + * and initialized. + */ + private static class LazyPushTransformer implements PushTransformer<Object, Object> { + + private String source; + private String target; + private int weight; + private WeakReference<ClassLoader> classLoader; + private String className; + private PushTransformer<Object, Object> transformer; + + public LazyPushTransformer(String source, String target, int weight, ClassLoader classLoader, String className) { + this.source = source; + this.target = target; + this.weight = weight; + this.classLoader = new WeakReference<ClassLoader>(classLoader); + this.className = className; + } + + /** + * Load and instantiate the transformer class. + * + * @return The transformer. + */ + @SuppressWarnings("unchecked") + private PushTransformer<Object, Object> getTransformer() { + if (transformer == null) { + try { + Class<PushTransformer<Object, Object>> transformerClass = + (Class<PushTransformer<Object, Object>>)Class.forName(className, true, classLoader.get()); + Constructor<PushTransformer<Object, Object>> constructor = transformerClass.getConstructor(); + transformer = constructor.newInstance(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return transformer; + } + + public String getSourceDataBinding() { + return source; + } + + public String getTargetDataBinding() { + return target; + } + + public int getWeight() { + return weight; + } + + public void transform(Object source, Object sink, TransformationContext context) { + getTransformer().transform(source, sink, context); + } + + } + + + //FIXME The following methods should be on a different class from + // extension point + + public List<Transformer> getTransformerChain(String sourceType, String resultType) { + loadTransformers(); + + String source = sourceType; + String result = resultType; + List<Transformer> transformers = new ArrayList<Transformer>(); + DirectedGraph<Object, Transformer>.Path path = graph.getShortestPath(source, result); + if (path == null) { + return null; + } + for (DirectedGraph<Object, Transformer>.Edge edge : path.getEdges()) { + transformers.add(edge.getValue()); + } + return transformers; + } + + @Override + public String toString() { + loadTransformers(); + + return graph.toString(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/ExceptionHandler.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/ExceptionHandler.java new file mode 100644 index 0000000000..131e8a3114 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/ExceptionHandler.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding; + +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * ExceptionHandler provides databinding-specific logic for exception handling + * + * @version $Rev$ $Date$ + */ +public interface ExceptionHandler { + /** + * Create an exception to wrap the fault data + * + * @param exceptionType The DataType for the exception + * @param message The error message + * @param faultInfo The databinding-specific fault data + * @param cause The protocol-specific error + * @return An instance of java exception to represent the fault + */ + Exception createException(DataType<DataType> exceptionType, String message, Object faultInfo, Throwable cause); + + /** + * Retrieve the fault info from a java exception + * + * @param exception The databinding-specific java exception that represents + * the fault data + * @return The databinding-specific fault data + */ + Object getFaultInfo(Exception exception); + + /** + * Introspect an exception class to figure out the fault data type + * + * @param exceptionDataType The exception class + * @return The data type for the fault + */ + DataType<?> getFaultType(DataType exceptionDataType); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.java new file mode 100755 index 0000000000..168a1052b3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.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.tuscany.sca.databinding; + +import java.util.Map; + +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * This interface will be used as a Tuscany system service to perform data mediations + * + * Mediate the data from one type to the other one + * + */ +public interface Mediator { + + /** + * Mediate the data from the source type to the target type + * @param source The data to be mediated + * @param sourceDataType Data type for the source data + * @param targetDataType Data type for the target data + * @param context + * @return + */ + Object mediate(Object source, DataType sourceDataType, DataType targetDataType, Map<String, Object> context); + /** + * Mediate the source data into the target which is a sink to receive the data + * @param source The data to be mediated + * @param target The sink to receive data + * @param sourceDataType Data type for the source data + * @param targetDataType Data type for the target data + */ + void mediate( + Object source, + Object target, + DataType sourceDataType, + DataType targetDataType, + Map<String, Object> context); + + /** + * Get the DataBindings used by this mediator. + * @return + */ + DataBindingExtensionPoint getDataBindings(); + + /** + * Get the Transformers used by this mediator. + * @return + */ + TransformerExtensionPoint getTransformers(); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.java new file mode 100644 index 0000000000..feed87e45f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.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.tuscany.sca.databinding; + +/** + * PullTransformer transforms data from one binding format to the other one which can be directly consumed + * + * @param <S> The source data type + * @param <R> the target data type + */ +public interface PullTransformer<S, R> extends Transformer { + /** + * Transform source data into the result type. + * + * @param source The source data + * @param context The context for the transformation + * @return The transformed result + */ + R transform(S source, TransformationContext context); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.java new file mode 100644 index 0000000000..80e5e4f0a3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.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.tuscany.sca.databinding; + +/** + * A transformer that pushes data from its source into the sink + * + * @param <S> + * @param <R> + */ +public interface PushTransformer<S, R> extends Transformer { + /** + * @param source The source data + * @param sink The sink to receive the data + * @param context + */ + void transform(S source, R sink, TransformationContext context); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.java new file mode 100644 index 0000000000..70ea431d57 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.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.tuscany.sca.databinding; + +import javax.xml.namespace.QName; + +/** + * Type Mapper between XML schema simple data types and java objects + */ +public interface SimpleTypeMapper { + /** + * Parse the XML lexical representation into a java object + * @param simpleType The XSD simple type + * @param value the XML lexical representation + * @param context The context of the transformation + * @return A java object for the XML value + */ + Object toJavaObject(QName simpleType, String value, TransformationContext context); + /** + * Create the XML lexical representation for a java object + * @param simpleType The XSD simple type + * @param obj The java object + * @param context The context of the transformation + * @return The XML lexical representation + */ + String toXMLLiteral(QName simpleType, Object obj, TransformationContext context); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.java new file mode 100755 index 0000000000..27818dc24f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding; + +import java.util.Map; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * Context for data transformation + * + */ +public interface TransformationContext { + + Operation getSourceOperation(); + void setSourceOperation(Operation sourceOperation); + Operation getTargetOperation(); + void setTargetOperation(Operation targetOperation); + + /** + * Get the source data type + * + * @return + */ + DataType getSourceDataType(); + + /** + * Get the target data type + * + * @return + */ + DataType getTargetDataType(); + + /** + * Set the source data type + * + * @param sourceDataType + */ + void setSourceDataType(DataType sourceDataType); + + /** + * Set the target data type + * + * @param targetDataType + */ + void setTargetDataType(DataType targetDataType); + + /** + * Get the classloader + * + * @return + */ + ClassLoader getClassLoader(); + + /** + * Get a map of metadata + * + * @return + */ + Map<String, Object> getMetadata(); + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.java new file mode 100755 index 0000000000..8d2b36482d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.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.tuscany.sca.databinding; + + +/** + * Reports problems during data transformation + */ +public class TransformationException extends RuntimeException { + + private static final long serialVersionUID = 7662385613693006428L; + private String sourceDataBinding; + private String targetDataBinding; + + public TransformationException() { + super(); + } + + public TransformationException(String message, Throwable cause) { + super(message, cause); + } + + public TransformationException(String message) { + super(message); + } + + public TransformationException(Throwable cause) { + super(cause); + } + + public String getSourceDataBinding() { + return sourceDataBinding; + } + + public void setSourceDataBinding(String sourceDataBinding) { + this.sourceDataBinding = sourceDataBinding; + } + + public String getTargetDataBinding() { + return targetDataBinding; + } + + public void setTargetDataBinding(String targetDataBinding) { + this.targetDataBinding = targetDataBinding; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.java new file mode 100755 index 0000000000..062f087a15 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.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.tuscany.sca.databinding; + +/** + * A transformer provides the data transformation from source type to target type. The cost of the transformation is + * modeled as weight. + */ +public interface Transformer { + /** + * Get the source type that this transformer transforms data from. The type is used as the key when the transformer + * is registered with TransformerRegistry. + * + * @return A key indentifying the source type + */ + String getSourceDataBinding(); + + /** + * Get the target type that this transformer transforms data into. The type is used as the key when the transformer + * is registered with TransformerRegistry. + * + * @return A key indentifying the target type + */ + String getTargetDataBinding(); + + /** + * Get the cost of the transformation. The weight can be used to choose the most efficient path if there are more + * than one available from the source to the target. + * + * @return An integer representing the cost of the transformation + */ + int getWeight(); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.java new file mode 100755 index 0000000000..1abae06754 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.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.tuscany.sca.databinding; + +import java.util.List; + +/** + * An extension point for data transformer extensions. + */ +public interface TransformerExtensionPoint { + + /** + * Register a transformer + * + * @param sourceDataBinding + * @param targetDataBinding + * @param weight + * @param transformer + */ + void addTransformer(String sourceDataBinding, + String targetDataBinding, + int weight, + Transformer transformer); + + /** + * Register a transformer + * + * @param transformer + */ + void addTransformer(Transformer transformer); + + /** + * Unregister a transformer + * + * @param sourceDataBinding + * @param targetDataBinding + * @return + */ + boolean removeTransformer(String sourceDataBinding, String targetDataBinding); + + /** + * Get the direct Transformer which can transform data from source type to + * result type + * + * @param sourceDataBinding + * @param targetDataBinding + * @return + */ + Transformer getTransformer(String sourceDataBinding, String targetDataBinding); + + /** + * Get the a chain of Transformers which can transform data from source type + * to result type + * + * @param sourceDataBinding + * @param targetDataBinding + * @return + */ + List<Transformer> getTransformerChain(String sourceDataBinding, String targetDataBinding); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.java new file mode 100644 index 0000000000..379a967c9c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; + +/** + * A contract for transformers to deal with wrapping/unwrapping for WSDL wrapper style operations + */ +public interface WrapperHandler<T> { + /** + * Create a wrapper element + * + * @param element The XSD element + * @param context The transformation context + * @return An object representing the wrapper element + */ + T create(ElementInfo element, TransformationContext context); + + /** + * Get the data type for the wrapper + * @param element The wrapper element + * @param childElements A list of child elements + * @param context The transformation context + * @return The data type of the wrapper, null if it's not a wrapper type + */ + DataType getWrapperType(ElementInfo element, List<ElementInfo> childElements, TransformationContext context); + + /** + * Check if the given data is an instance of the wrapper + * @param wrapper + * @param element + * @param childElements + * @param context + * @return + */ + boolean isInstance(Object wrapper, + ElementInfo element, + List<ElementInfo> childElements, + TransformationContext context); + + /** + * Set child element for the wrapper + * + * @param wrapper The wrapper + * @param i The index + * @param childElement The XSD element + * @param value The value of the child + */ + void setChild(T wrapper, int i, ElementInfo childElement, Object value); + + /** + * Get a list of child elements from the wrapper + * @param wrapper + * @param childElements + * @param context + * @return child elements under the wrapper + */ + List getChildren(T wrapper, List<ElementInfo> childElements, TransformationContext context); + + // Object getChild(T wrapper, ElementInfo childElement, TransformationContext context); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.java new file mode 100644 index 0000000000..1d0e117d34 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.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.tuscany.sca.databinding.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Used to demarcate expected data types for an operation + * + * @version $Rev$ $Date$ + */ +@Target({TYPE, METHOD}) +@Retention(RUNTIME) +public @interface DataBinding { + + /** + * Returns the unique name of the data binding + * @return the unique name of the data binding + */ + String value(); + boolean wrapperStyle() default false; + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.java new file mode 100644 index 0000000000..2714391e75 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.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.tuscany.sca.databinding.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Used to demarcate expected data types for parameters and return type + * + * @version $Rev$ $Date$ + */ +@Target( {METHOD, PARAMETER}) +@Retention(RUNTIME) +public @interface DataType { + + /** + * Returns the unique name of the data binding + * @return the unique name of the data binding + */ + String value(); + + /** + * Additional attributes to further describe the data type + * @return + */ + String[] attributes() default {}; + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/BaseDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/BaseDataBinding.java new file mode 100644 index 0000000000..0bc9d3c192 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/BaseDataBinding.java @@ -0,0 +1,130 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import java.lang.annotation.Annotation; + +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.ExceptionHandler; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; + +/** + * Base Implementation of DataBinding + * + * @version $Rev$ $Date$ + */ +public abstract class BaseDataBinding implements DataBinding { + + private Class<?> baseType; + + private String name; + private String[] aliases; + + /** + * Create a databinding with the base java type whose name will be used as + * the name of the databinding + * + * @param baseType The base java class or interface representing the + * databinding, for example, org.w3c.dom.Node + */ + protected BaseDataBinding(Class<?> baseType) { + this(baseType.getName(), null, baseType); + } + + /** + * Create a databinding with the name and base java type + * + * @param name The name of the databinding + * @param baseType The base java class or interface representing the + * databinding, for example, org.w3c.dom.Node + */ + protected BaseDataBinding(String name, Class<?> baseType) { + this(name, null, baseType); + } + + /** + * Create a databinding with the name and base java type + * + * @param name The name of the databinding + * @param aliases The aliases of the databinding + * @param baseType The base java class or interface representing the + * databinding, for example, org.w3c.dom.Node + */ + protected BaseDataBinding(String name, String[] aliases, Class<?> baseType) { + this.name = name; + this.baseType = baseType; + this.aliases = aliases; + } + + @SuppressWarnings("unchecked") + public boolean introspect(DataType type, Annotation[] annotations) { + assert type != null; + Class cls = type.getPhysical(); + if (baseType != null && baseType.isAssignableFrom(cls)) { + type.setDataBinding(getName()); + type.setLogical(baseType); + return true; + } + return false; + } + + public DataType introspect(Object value) { + if (value == null) { + return null; + } else { + DataType<Class> dataType = new DataTypeImpl<Class>(value.getClass(), value.getClass()); + if (introspect(dataType, null)) { + return dataType; + } else { + return null; + } + } + } + + public final String getName() { + return name; + } + + /** + * @see org.apache.tuscany.sca.databinding.DataBinding#getWrapperHandler() + */ + public WrapperHandler getWrapperHandler() { + return null; + } + + public ExceptionHandler getExceptionHandler() { + return null; + } + + public Object copy(Object object) { + return object; + } + + public SimpleTypeMapper getSimpleTypeMapper() { + return new SimpleTypeMapperImpl(); + } + + public String[] getAliases() { + return aliases; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/BaseTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/BaseTransformer.java new file mode 100644 index 0000000000..0efb7e41b5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/BaseTransformer.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.tuscany.sca.databinding.impl; + +import org.apache.tuscany.sca.databinding.Transformer; + +/** + * Base Implementation of Transformer which provides the registration to the + * transformer registry + * + * @version $Rev$ $Date$ + */ +public abstract class BaseTransformer<S, T> implements Transformer { + + protected BaseTransformer() { + super(); + } + + protected abstract Class getSourceType(); + + protected abstract Class getTargetType(); + + public String getSourceDataBinding() { + return getSourceType().getName(); + } + + public String getTargetDataBinding() { + return getTargetType().getName(); + } + + public int getWeight() { + // default to 50 + return 50; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DOMHelper.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DOMHelper.java new file mode 100644 index 0000000000..b9fa7ca615 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DOMHelper.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * Helper for DOM + */ +public final class DOMHelper { + private static DocumentBuilderFactory FACTORY; + + private DOMHelper() { + } + + public static Document newDocument() throws ParserConfigurationException { + return newDocumentBuilder().newDocument(); + } + + public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { + init(); + return FACTORY.newDocumentBuilder(); + } + + /** + * + */ + private synchronized static void init() { + if (FACTORY == null) { + FACTORY = DocumentBuilderFactory.newInstance(); + FACTORY.setNamespaceAware(true); + } + } + + public static QName getQName(Node node) { + String ns = node.getNamespaceURI(); + if (ns == null) { + ns = ""; + } + // node.getLocalName() will return null if it is created using DOM Level + // 1 method + // such as createElement() + return new QName(ns, node.getNodeName()); + } + + public static Element createElement(Document document, QName name) { + String prefix = name.getPrefix(); + String qname = + (prefix != null && prefix.length() > 0) ? prefix + ":" + name.getLocalPart() : name.getLocalPart(); + return document.createElementNS(name.getNamespaceURI(), qname); + } + + /** + * Wrap an element as a DOM document + * @param node + * @return + */ + public static Document promote(Node node) { + if (node instanceof Document) { + return (Document)node; + } + Element element = (Element)node; + Document doc = element.getOwnerDocument(); + if (doc.getDocumentElement() == element) { + return doc; + } + doc = (Document)element.getOwnerDocument().cloneNode(false); + Element schema = (Element)doc.importNode(element, true); + doc.appendChild(schema); + Node parent = element.getParentNode(); + while (parent instanceof Element) { + Element root = (Element)parent; + NamedNodeMap nodeMap = root.getAttributes(); + for (int i = 0; i < nodeMap.getLength(); i++) { + Attr attr = (Attr)nodeMap.item(i); + String name = attr.getName(); + if ("xmlns".equals(name) || name.startsWith("xmlns:")) { + if (schema.getAttributeNode(name) == null) { + schema.setAttributeNodeNS((Attr)doc.importNode(attr, true)); + } + } + } + parent = parent.getParentNode(); + } + return doc; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java new file mode 100755 index 0000000000..6ecc1c6cd8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java @@ -0,0 +1,363 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Directed, weighted graph + * + * @param <V> The type of vertex object + * @param <E> The type of edge object + */ +public class DirectedGraph<V, E> { + private final Map<V, Vertex> vertices = new HashMap<V, Vertex>(); + + /** + * Key for the shortest path cache + */ + private final class VertexPair { + private Vertex source; + + private Vertex target; + + /** + * @param source + * @param target + */ + private VertexPair(Vertex source, Vertex target) { + super(); + this.source = source; + this.target = target; + } + + @Override + public boolean equals(Object object) { + if (!VertexPair.class.isInstance(object)) { + return false; + } + VertexPair pair = (VertexPair)object; + return source == pair.source && target == pair.target; + } + + @Override + public int hashCode() { + int x = source == null ? 0 : source.hashCode(); + int y = target == null ? 0 : target.hashCode(); + return x ^ y; + } + + } + + private final Map<VertexPair, Path> paths = new HashMap<VertexPair, Path>(); + + /** + * Vertex of a graph + */ + public final class Vertex { + private V value; + + // TODO: Do we want to support multiple edges for a vertex pair? If so, + // we should use a List instead of Map + private Map<Vertex, Edge> outEdges = new HashMap<Vertex, Edge>(); + + private Vertex(V value) { + this.value = value; + } + + @Override + public String toString() { + return "(" + value + ")"; + } + + public V getValue() { + return value; + } + + public Map<Vertex, Edge> getOutEdges() { + return outEdges; + } + + } + + /** + * An Edge connects two vertices in one direction + */ + public final class Edge { + private Vertex sourceVertex; + + private Vertex targetVertex; + + private E value; + + private int weight; + + public Edge(Vertex source, Vertex target, E value, int weight) { + this.sourceVertex = source; + this.targetVertex = target; + this.value = value; + this.weight = weight; + } + + @Override + public String toString() { + return sourceVertex + "->" + targetVertex + "[" + value + "," + weight + "]"; + } + + public E getValue() { + return value; + } + + public void setValue(E value) { + this.value = value; + } + + public Vertex getTargetVertex() { + return targetVertex; + } + + public void setTargetVertex(Vertex vertex) { + this.targetVertex = vertex; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public Vertex getSourceVertex() { + return sourceVertex; + } + + public void setSourceVertex(Vertex sourceVertex) { + this.sourceVertex = sourceVertex; + } + } + + private final class Node implements Comparable<Node> { + + private long distance = Integer.MAX_VALUE; + + private Node previous; // NOPMD by rfeng on 9/26/06 9:17 PM + + private Vertex vertex; // NOPMD by rfeng on 9/26/06 9:17 PM + + private Node(Vertex vertex) { + this.vertex = vertex; + } + + public int compareTo(Node o) { + return (distance > o.distance) ? 1 : ((distance == o.distance) ? 0 : -1); + } + } + + public void addEdge(V source, V target, E edgeValue, int weight) { + Vertex s = getVertex(source); + if (s == null) { + s = new Vertex(source); + vertices.put(source, s); + } + Vertex t = getVertex(target); + if (t == null) { + t = new Vertex(target); + vertices.put(target, t); + } + Edge edge = new Edge(s, t, edgeValue, weight); + s.outEdges.put(t, edge); + } + + public Vertex getVertex(V source) { + Vertex s = vertices.get(source); + return s; + } + + public boolean removeEdge(V source, V target) { + Vertex s = getVertex(source); + if (s == null) { + return false; + } + + Vertex t = getVertex(target); + if (t == null) { + return false; + } + + return s.outEdges.remove(t) != null; + + } + + public Edge getEdge(Vertex source, Vertex target) { + return source.outEdges.get(target); + } + + public Edge getEdge(V source, V target) { + return getEdge(getVertex(source), getVertex(target)); + } + + /** + * Get the shortes path from the source vertex to the target vertex using + * Dijkstra's algorithm. If there's no path, null will be returned. If the + * source is the same as the target, it returns a path with empty edges with + * weight 0. + * + * @param sourceValue The value identifies the source + * @param targetValue The value identifies the target + * @return The shortest path + */ + public Path getShortestPath(V sourceValue, V targetValue) { + Vertex source = getVertex(sourceValue); + if (source == null) { + return null; + } + Vertex target = getVertex(targetValue); + if (target == null) { + return null; + } + + VertexPair pair = new VertexPair(source, target); + if (paths.containsKey(pair)) { + return paths.get(pair); + } + + // HACK: To support same vertex + if (source == target) { + Path path = new Path(); + Edge edge = getEdge(source, target); + if (edge != null) { + path.addEdge(edge); + } + paths.put(pair, path); + return path; + } + + Map<Vertex, Node> nodes = new HashMap<Vertex, Node>(); + for (Vertex v : vertices.values()) { + Node node = new Node(v); + if (v == source) { + node.distance = 0; + } + nodes.put(v, node); + } + + Set<Node> otherNodes = new HashSet<Node>(nodes.values()); + Set<Node> nodesOnPath = new HashSet<Node>(); + while (!otherNodes.isEmpty()) { + Node nextNode = extractMin(otherNodes); + if (nextNode.vertex == target) { + Path path = getPath(nextNode); + paths.put(pair, path); // Cache it + return path; + } + nodesOnPath.add(nextNode); + for (Edge edge : nextNode.vertex.outEdges.values()) { + Node adjacentNode = nodes.get(edge.targetVertex); + if (nextNode.distance + edge.weight < adjacentNode.distance) { + adjacentNode.distance = nextNode.distance + edge.weight; + adjacentNode.previous = nextNode; + } + } + } + paths.put(pair, null); // Cache it + return null; + } + + /** + * Searches for the vertex u in the vertex set Q that has the least d[u] + * value. That vertex is removed from the set Q and returned to the user. + * + * @param nodes + * @return + */ + private Node extractMin(Set<Node> nodes) { + Node node = Collections.min(nodes); + nodes.remove(node); + return node; + } + + /** + * The path between two vertices + */ + public final class Path { + private List<Edge> edges = new LinkedList<Edge>(); + + private int weight; + + public int getWeight() { + return weight; + } + + public List<Edge> getEdges() { + return edges; + } + + public void addEdge(Edge edge) { + edges.add(0, edge); + weight += edge.weight; + } + + @Override + public String toString() { + return edges + ", " + weight; + } + } + + private Path getPath(Node t) { + if (t.distance == Integer.MAX_VALUE) { + return null; + } + Path path = new Path(); + Node u = t; + while (u.previous != null) { + Edge edge = getEdge(u.previous.vertex, u.vertex); + path.addEdge(edge); + u = u.previous; + } + return path; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + for (Vertex v : vertices.values()) { + sb.append(v.outEdges.values()).append("\n"); + } + return sb.toString(); + } + + public Map<V, Vertex> getVertices() { + return vertices; + } + + public void addGraph(DirectedGraph<V, E> otherGraph) { + for (Vertex v : otherGraph.vertices.values()) { + for (Edge e : v.outEdges.values()) { + addEdge(e.sourceVertex.value, e.targetVertex.value, e.value, e.weight); + } + } + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.java new file mode 100644 index 0000000000..d1dd6f28f0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.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.tuscany.sca.databinding.impl; + +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * This is a special transformer to transform the output from one IDL to the + * other one + */ +public class Group2GroupTransformer extends BaseTransformer<Object, Object> implements + PullTransformer<Object, Object> { + + protected Mediator mediator; + + /** + * @param wrapperHandler + */ + public Group2GroupTransformer() { + super(); + } + + /** + * @param mediator the mediator to set + */ + public void setMediator(Mediator mediator) { + this.mediator = mediator; + } + + @Override + public String getSourceDataBinding() { + return GroupDataBinding.NAME; + } + + @Override + public String getTargetDataBinding() { + return GroupDataBinding.NAME; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getSourceType() + */ + @Override + protected Class getSourceType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.impl.BaseTransformer#getTargetType() + */ + @Override + protected Class getTargetType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.Transformer#getWeight() + */ + @Override + public int getWeight() { + return 10; + } + + @SuppressWarnings("unchecked") + public Object transform(Object source, TransformationContext context) { + DataType<DataType> sourceType = context.getSourceDataType(); + DataType<DataType> targetType = context.getTargetDataType(); + + return mediator.mediate(source, sourceType.getLogical(), targetType.getLogical(), context.getMetadata()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.java new file mode 100644 index 0000000000..0cc87f8325 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.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.tuscany.sca.databinding.impl; + +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * The base class for a special databinding which represents a group of other databindings + * + * @version $Rev$ $Date$ + */ +public abstract class GroupDataBinding extends BaseDataBinding { + public static final String NAME = "databinding:group"; + + /** + * Marker type is a java class or interface representing the data format. + */ + protected Class[] markerTypes; + + public GroupDataBinding(Class[] types) { + super(NAME, null, GroupDataBinding.class); + this.markerTypes = types; + } + + @SuppressWarnings("unchecked") + @Override + public boolean introspect(DataType type, Annotation[] annotations) { + if (markerTypes == null) { + return false; + } + Type physical = type.getPhysical(); + if (physical instanceof ParameterizedType) { + physical = ((ParameterizedType)physical).getRawType(); + } + if (!(physical instanceof Class)) { + return false; + } + Class cls = (Class)physical; + for (Class<?> c : markerTypes) { + if (isTypeOf(c, cls)) { + type.setDataBinding(getDataBinding(c)); + type.setLogical(getLogical(cls, annotations)); + return true; + } + } + return false; + } + + /** + * Test if the given type is a subtype of the base type + * @param markerType + * @param type + * @return + */ + protected boolean isTypeOf(Class<?> markerType, Class<?> type) { + return markerType.isAssignableFrom(type); + } + + /** + * Derive the databinding name from a base class + * @param baseType + * @return + */ + protected String getDataBinding(Class<?> baseType) { + return baseType.getName(); + } + + /** + * Get the logical type + * @param type The java type + * @param annotations + * @return + */ + protected abstract Object getLogical(Class<?> type, Annotation[] annotations); + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.java new file mode 100644 index 0000000000..50b5bf6e8d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from a simple java object to a databinding's representation + */ +public abstract class Java2SimpleTypeTransformer<T> extends BaseTransformer<Object, T> implements + PullTransformer<Object, T> { + + protected SimpleTypeMapper mapper; + + public Java2SimpleTypeTransformer() { + this.mapper = new SimpleTypeMapperImpl(); + } + + public Java2SimpleTypeTransformer(SimpleTypeMapper mapper) { + this.mapper = (mapper != null) ? mapper : new SimpleTypeMapperImpl(); + } + + public T transform(Object source, TransformationContext context) { + XMLType xmlType = (XMLType) context.getTargetDataType().getLogical(); + String text = mapper.toXMLLiteral(xmlType.getTypeName(), source, context); + return createElement(xmlType.getElementName(), text, context); + } + + @Override + public Class getSourceType() { + return Object.class; + } + + @Override + public int getWeight() { + return 10000; + } + + protected abstract T createElement(QName element, String literal, TransformationContext context); + + @Override + public String getSourceDataBinding() { + return SimpleJavaDataBinding.NAME; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.java new file mode 100644 index 0000000000..e995d17fd9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.java @@ -0,0 +1,165 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; + +/** + * Default Mediator implementation + */ +public class MediatorImpl implements Mediator { + + private DataBindingExtensionPoint dataBindings; + private TransformerExtensionPoint transformers; + + public MediatorImpl(DataBindingExtensionPoint dataBindings, TransformerExtensionPoint transformers) { + this.dataBindings = dataBindings; + this.transformers = transformers; + } + + @SuppressWarnings("unchecked") + public Object mediate(Object source, DataType sourceDataType, DataType targetDataType, Map<String, Object> metadata) { + if (sourceDataType == null || sourceDataType.getDataBinding() == null) { + sourceDataType = dataBindings.introspectType(source); + } + if (sourceDataType == null) { + return source; + } else if (sourceDataType.equals(targetDataType)) { + return source; + } + + List<Transformer> path = getTransformerChain(sourceDataType, targetDataType); + + Object result = source; + int size = path.size(); + int i = 0; + while (i < size) { + Transformer transformer = path.get(i); + TransformationContext context = + createTransformationContext(sourceDataType, targetDataType, size, i, transformer, metadata); + // the source and target type + if (transformer instanceof PullTransformer) { + // For intermediate node, set data type to null + result = ((PullTransformer)transformer).transform(result, context); + } else if (transformer instanceof PushTransformer) { + DataPipeTransformer dataPipeFactory = (i < size - 1) ? (DataPipeTransformer)path.get(++i) : null; + DataPipe dataPipe = dataPipeFactory == null ? null : dataPipeFactory.newInstance(); + ((PushTransformer)transformer).transform(result, dataPipe.getSink(), context); + result = dataPipe.getResult(); + } + i++; + } + + return result; + } + + private TransformationContext createTransformationContext(DataType sourceDataType, + DataType targetDataType, + int size, + int index, + Transformer transformer, + Map<String, Object> metadata) { + DataType sourceType = + (index == 0) ? sourceDataType : new DataTypeImpl<Object>(transformer.getSourceDataBinding(), Object.class, + sourceDataType.getLogical()); + DataType targetType = + (index == size - 1) ? targetDataType : new DataTypeImpl<Object>(transformer.getTargetDataBinding(), + Object.class, targetDataType.getLogical()); + + //FIXME The classloader should be passed in + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + TransformationContext context = new TransformationContextImpl(sourceType, targetType, classLoader, metadata); + return context; + } + + @SuppressWarnings("unchecked") + public void mediate(Object source, + Object target, + DataType sourceDataType, + DataType targetDataType, + Map<String, Object> metadata) { + if (source == null) { + // Shortcut for null value + return; + } + if (sourceDataType == null || sourceDataType.getDataBinding() == null) { + sourceDataType = dataBindings.introspectType(source); + } + if (sourceDataType == null) { + return; + } else if (sourceDataType.equals(targetDataType)) { + return; + } + + List<Transformer> path = getTransformerChain(sourceDataType, targetDataType); + Object result = source; + int size = path.size(); + for (int i = 0; i < size; i++) { + Transformer transformer = path.get(i); + TransformationContext context = + createTransformationContext(sourceDataType, targetDataType, size, i, transformer, metadata); + + if (transformer instanceof PullTransformer) { + result = ((PullTransformer)transformer).transform(result, context); + } else if (transformer instanceof PushTransformer) { + DataPipeTransformer dataPipeFactory = (i < size - 1) ? (DataPipeTransformer)path.get(++i) : null; + DataPipe dataPipe = dataPipeFactory == null ? null : dataPipeFactory.newInstance(); + Object sink = dataPipe != null ? dataPipe.getSink() : target; + ((PushTransformer)transformer).transform(result, sink, context); + result = (dataPipe != null) ? dataPipe.getResult() : null; + } + } + } + + private List<Transformer> getTransformerChain(DataType sourceDataType, DataType targetDataType) { + String sourceId = sourceDataType.getDataBinding(); + String targetId = targetDataType.getDataBinding(); + List<Transformer> path = transformers.getTransformerChain(sourceId, targetId); + if (path == null) { + TransformationException ex = new TransformationException("No path found for the transformation"); + ex.setSourceDataBinding(sourceId); + ex.setTargetDataBinding(targetId); + throw ex; + } + return path; + } + + public DataBindingExtensionPoint getDataBindings() { + return dataBindings; + } + + public TransformerExtensionPoint getTransformers() { + return transformers; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.java new file mode 100755 index 0000000000..e2db8c5834 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; + +/** + * A utility class to connect PushTransformer and DataPipe to create a + * PullTransformer + * + * @param <S> Source type + * @param <I> Intermidate type + * @param <R> Result type + */ +public class PipedTransformer<S, I, R> implements PullTransformer<S, R> { + private PushTransformer<S, I> pusher; + + private DataPipeTransformer<I, R> pipe; + + /** + * @param pumper + * @param pipe + */ + public PipedTransformer(PushTransformer<S, I> pumper, DataPipeTransformer<I, R> pipe) { + super(); + this.pusher = pumper; + this.pipe = pipe; + } + + public R transform(S source, TransformationContext context) { + DataPipe<I, R> dataPipe = pipe.newInstance(); + pusher.transform(source, dataPipe.getSink(), context); + return dataPipe.getResult(); + } + + public String getSourceDataBinding() { + return pusher.getSourceDataBinding(); + } + + public String getTargetDataBinding() { + return pipe.getTargetDataBinding(); + } + + public int getWeight() { + return pusher.getWeight() + pipe.getWeight(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/ServiceConfigurationUtil.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/ServiceConfigurationUtil.java new file mode 100644 index 0000000000..79e68a4f3b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/ServiceConfigurationUtil.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.impl; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +public class ServiceConfigurationUtil { + + /** + * Read the service name from a configuration file + * + * @param classLoader + * @param name The name of the service class + * @return A class name which extends/implements the service class + * @throws IOException + */ + public static List<String> getServiceClassNames(ClassLoader classLoader, String name) throws IOException { + List<String> classNames = new ArrayList<String>(); + for (URL url: Collections.list(classLoader.getResources("META-INF/services/" + name))) { + InputStream is = url.openStream(); + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(is)); + while (true) { + String line = reader.readLine(); + if (line == null) + break; + line = line.trim(); + if (!line.startsWith("#") && !"".equals(line)) { + classNames.add(line.trim()); + } + } + } finally { + if (reader != null) + reader.close(); + if (is != null) { + try { + is.close(); + } catch (IOException ioe) {} + } + } + } + return classNames; + } + + /** + * Parse a service declaration in the form class;attr=value,attr=value and + * return a map of attributes + * + * @param declaration + * @return a map of attributes + */ + public static Map<String, String> parseServiceDeclaration(String declaration) { + Map<String, String> attributes = new HashMap<String, String>(); + StringTokenizer tokens = new StringTokenizer(declaration); + String className = tokens.nextToken(";"); + if (className != null) + attributes.put("class", className); + for (; tokens.hasMoreTokens(); ) { + String key = tokens.nextToken("=").substring(1); + if (key == null) + break; + String value = tokens.nextToken(",").substring(1); + if (value == null) + break; + attributes.put(key, value); + } + return attributes; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.java new file mode 100644 index 0000000000..5d7776fa78 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.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.tuscany.sca.databinding.impl; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from a databinding's representation of simple + * types to Java Objects + */ +public abstract class SimpleType2JavaTransformer<T> extends BaseTransformer<T, Object> implements + PullTransformer<T, Object> { + + protected SimpleTypeMapper mapper; + + public SimpleType2JavaTransformer() { + this.mapper = new SimpleTypeMapperImpl(); + } + + public SimpleType2JavaTransformer(SimpleTypeMapper mapper) { + this.mapper = (mapper != null) ? mapper : new SimpleTypeMapperImpl(); + } + + public Object transform(T source, TransformationContext context) { + XMLType xmlType = (XMLType)context.getSourceDataType().getLogical(); + QName type = (xmlType != null) ? xmlType.getTypeName() : null; + if (type == null) { + xmlType = (XMLType)context.getTargetDataType().getLogical(); + type = (xmlType != null) ? xmlType.getTypeName() : null; + } + Object result = mapper.toJavaObject(type, getText(source), context); + close(source); + return result; + } + + @Override + public Class getTargetType() { + return Object.class; + } + + @Override + public int getWeight() { + // Cannot be used for imtermediate + return 10000; + } + + /** + * Get the string value from the source + * @param source + * @return A string + */ + protected abstract String getText(T source); + + /** + * To be overrided by the subclass + * @param source + */ + protected void close(T source) { + } + + @Override + public String getTargetDataBinding() { + return SimpleJavaDataBinding.NAME; + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java new file mode 100644 index 0000000000..c36ebb04c5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java @@ -0,0 +1,396 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.impl; + +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; + +public class SimpleTypeMapperImpl extends XSDDataTypeConverter implements SimpleTypeMapper { + + public static final Map<Class, String> JAVA2XML = new HashMap<Class, String>(); + + public static final String URI_2001_SCHEMA_XSD = "http://www.w3.org/2001/XMLSchema"; + + public static final Map<String, Class> XML2JAVA = new HashMap<String, Class>(); + + public static final QName XSD_ANY = new QName(URI_2001_SCHEMA_XSD, "any"); + + public static final QName XSD_ANYSIMPLETYPE = new QName(URI_2001_SCHEMA_XSD, "anySimpleType"); + + public static final QName XSD_ANYTYPE = new QName(URI_2001_SCHEMA_XSD, "anyType"); + + public static final QName XSD_ANYURI = new QName(URI_2001_SCHEMA_XSD, "anyURI"); + + public static final QName XSD_BASE64 = new QName(URI_2001_SCHEMA_XSD, "base64Binary"); + + public static final QName XSD_BOOLEAN = new QName(URI_2001_SCHEMA_XSD, "boolean"); + + public static final QName XSD_BYTE = new QName(URI_2001_SCHEMA_XSD, "byte"); + + public static final QName XSD_DATE = new QName(URI_2001_SCHEMA_XSD, "date"); + + public static final QName XSD_DATETIME = new QName(URI_2001_SCHEMA_XSD, "dateTime"); + + public static final QName XSD_DAY = new QName(URI_2001_SCHEMA_XSD, "gDay"); + + public static final QName XSD_DECIMAL = new QName(URI_2001_SCHEMA_XSD, "decimal"); + + public static final QName XSD_DOUBLE = new QName(URI_2001_SCHEMA_XSD, "double"); + + public static final QName XSD_DURATION = new QName(URI_2001_SCHEMA_XSD, "duration"); + + public static final QName XSD_ENTITIES = new QName(URI_2001_SCHEMA_XSD, "ENTITIES"); + + public static final QName XSD_ENTITY = new QName(URI_2001_SCHEMA_XSD, "ENTITY"); + + public static final QName XSD_FLOAT = new QName(URI_2001_SCHEMA_XSD, "float"); + + public static final QName XSD_HEXBIN = new QName(URI_2001_SCHEMA_XSD, "hexBinary"); + + public static final QName XSD_IDREF = new QName(URI_2001_SCHEMA_XSD, "IDREF"); + + public static final QName XSD_IDREFS = new QName(URI_2001_SCHEMA_XSD, "IDREFS"); + + public static final QName XSD_INT = new QName(URI_2001_SCHEMA_XSD, "int"); + + public static final QName XSD_INTEGER = new QName(URI_2001_SCHEMA_XSD, "integer"); + + public static final QName XSD_LONG = new QName(URI_2001_SCHEMA_XSD, "long"); + + public static final QName XSD_MONTH = new QName(URI_2001_SCHEMA_XSD, "gMonth"); + + public static final QName XSD_MONTHDAY = new QName(URI_2001_SCHEMA_XSD, "gMonthDay"); + + public static final QName XSD_NAME = new QName(URI_2001_SCHEMA_XSD, "Name"); + + public static final QName XSD_NCNAME = new QName(URI_2001_SCHEMA_XSD, "NCName"); + + public static final QName XSD_NEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "negativeInteger"); + + public static final QName XSD_NMTOKEN = new QName(URI_2001_SCHEMA_XSD, "NMTOKEN"); + + public static final QName XSD_NMTOKENS = new QName(URI_2001_SCHEMA_XSD, "NMTOKENS"); + + public static final QName XSD_NONNEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "nonNegativeInteger"); + + public static final QName XSD_NONPOSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "nonPositiveInteger"); + + public static final QName XSD_NORMALIZEDSTRING = new QName(URI_2001_SCHEMA_XSD, "normalizedString"); + + public static final QName XSD_NOTATION = new QName(URI_2001_SCHEMA_XSD, "NOTATION"); + + public static final QName XSD_POSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "positiveInteger"); + + public static final QName XSD_QNAME = new QName(URI_2001_SCHEMA_XSD, "QName"); + + public static final QName XSD_SHORT = new QName(URI_2001_SCHEMA_XSD, "short"); + + public static final Map<String, TypeInfo> XSD_SIMPLE_TYPES = new HashMap<String, TypeInfo>(); + + public static final QName XSD_STRING = new QName(URI_2001_SCHEMA_XSD, "string"); + + public static final QName XSD_TIME = new QName(URI_2001_SCHEMA_XSD, "time"); + + public static final QName XSD_TOKEN = new QName(URI_2001_SCHEMA_XSD, "token"); + + public static final QName XSD_UNSIGNEDBYTE = new QName(URI_2001_SCHEMA_XSD, "unsignedByte"); + + public static final QName XSD_UNSIGNEDINT = new QName(URI_2001_SCHEMA_XSD, "unsignedInt"); + + public static final QName XSD_UNSIGNEDLONG = new QName(URI_2001_SCHEMA_XSD, "unsignedLong"); + + public static final QName XSD_UNSIGNEDSHORT = new QName(URI_2001_SCHEMA_XSD, "unsignedShort"); + + public static final QName XSD_YEAR = new QName(URI_2001_SCHEMA_XSD, "gYear"); + + public static final QName XSD_YEARMONTH = new QName(URI_2001_SCHEMA_XSD, "gYearMonth"); + + private static final String[] XSD_TYPE_NAMES = + {"string", "boolean", "double", "float", "int", "integer", "long", "short", "byte", "decimal", "base64Binary", + "hexBinary", "anySimpleType", "anyType", "any", "QName", "dateTime", "date", "time", "normalizedString", + "token", "unsignedLong", "unsignedInt", "unsignedShort", "unsignedByte", "positiveInteger", "negativeInteger", + "nonNegativeInteger", "nonPositiveInteger", "gYearMonth", "gMonthDay", "gYear", "gMonth", "gDay", "duration", + "Name", "NCName", "NMTOKEN", "NMTOKENS", "NOTATION", "ENTITY", "ENTITIES", "IDREF", "IDREFS", "anyURI", + "language", "ID"}; + + static { + for (String type : XSD_TYPE_NAMES) { + TypeInfo simpleType = new TypeInfo(new QName(URI_2001_SCHEMA_XSD, type), true, null); + XSD_SIMPLE_TYPES.put(type, simpleType); + } + } + + static { + JAVA2XML.put(boolean.class, "boolean"); + JAVA2XML.put(byte.class, "byte"); + JAVA2XML.put(short.class, "short"); + JAVA2XML.put(int.class, "int"); + JAVA2XML.put(long.class, "long"); + JAVA2XML.put(float.class, "float"); + JAVA2XML.put(double.class, "double"); + JAVA2XML.put(Boolean.class, "boolean"); + JAVA2XML.put(Byte.class, "byte"); + JAVA2XML.put(Short.class, "short"); + JAVA2XML.put(Integer.class, "int"); + JAVA2XML.put(Long.class, "long"); + JAVA2XML.put(Float.class, "float"); + JAVA2XML.put(Double.class, "double"); + JAVA2XML.put(java.lang.String.class, "string"); + JAVA2XML.put(java.math.BigInteger.class, "integer"); + JAVA2XML.put(java.math.BigDecimal.class, "decimal"); + JAVA2XML.put(java.util.Calendar.class, "dateTime"); + JAVA2XML.put(java.util.Date.class, "dateTime"); + JAVA2XML.put(javax.xml.namespace.QName.class, "QName"); + JAVA2XML.put(java.net.URI.class, "string"); + JAVA2XML.put(javax.xml.datatype.XMLGregorianCalendar.class, "anySimpleType"); + JAVA2XML.put(javax.xml.datatype.Duration.class, "duration"); + JAVA2XML.put(java.lang.Object.class, "anyType"); + JAVA2XML.put(java.awt.Image.class, "base64Binary"); + JAVA2XML.put(byte[].class, "base64Binary"); + // java2XSD.put(javax.activation.DataHandler.class, "base64Binary"); + JAVA2XML.put(javax.xml.transform.Source.class, "base64Binary"); + JAVA2XML.put(java.util.UUID.class, "string"); + } + + static { + XML2JAVA.put("string", java.lang.String.class); + XML2JAVA.put("integer", java.math.BigInteger.class); + XML2JAVA.put("int", int.class); + XML2JAVA.put("long", long.class); + XML2JAVA.put("short", short.class); + XML2JAVA.put("decimal", java.math.BigDecimal.class); + XML2JAVA.put("float", float.class); + XML2JAVA.put("double", double.class); + XML2JAVA.put("boolean", boolean.class); + XML2JAVA.put("byte", byte.class); + XML2JAVA.put("QName", javax.xml.namespace.QName.class); + XML2JAVA.put("dateTime", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("base64Binary", byte[].class); + XML2JAVA.put("hexBinary", byte[].class); + XML2JAVA.put("unsignedInt", long.class); + XML2JAVA.put("unsignedShort", int.class); + XML2JAVA.put("unsignedByte", short.class); + XML2JAVA.put("time", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("date", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gDay", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gMonth", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gYear", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gYearMonth", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gMonthDay", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("anySimpleType", java.lang.Object.class); // For elements + // XML2JAVA.put("anySimpleType", java.lang.String.class); // For + // attributes + XML2JAVA.put("duration", javax.xml.datatype.Duration.class); + XML2JAVA.put("NOTATION", javax.xml.namespace.QName.class); + } + + private DatatypeFactory factory; + + public SimpleTypeMapperImpl() { + super(); + try { + this.factory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new IllegalArgumentException(e); + } + } + + public static Class getJavaType(QName xmlType) { + if (URI_2001_SCHEMA_XSD.equals(xmlType.getNamespaceURI())) { + return XML2JAVA.get(xmlType.getLocalPart()); + } else { + return null; + } + } + + public static TypeInfo getXMLType(Class javaType) { + return XSD_SIMPLE_TYPES.get(JAVA2XML.get(javaType)); + } + + public Object toJavaObject(QName simpleType, String literal, TransformationContext context) { + /** + * <ul> + * <li>xsd:string --- java.lang.String + * <li>xsd:integer --- java.math.BigInteger + * <li>xsd:int --- int + * <li>xsd:long --- long + * <li>xsd:short --- short + * <li>xsd:decimal --- java.math.BigDecimal + * <li>xsd:float --- float + * <li>xsd:double --- double + * <li>xsd:boolean --- boolean + * <li>xsd:byte --- byte + * <li>xsd:QName --- javax.xml.namespace.QName + * <li>xsd:dateTime --- javax.xml.datatype.XMLGregorianCalendar + * <li>xsd:base64Binary --- byte[] + * <li>xsd:hexBinary --- byte[] + * <li>xsd:unsignedInt --- long + * <li>xsd:unsignedShort --- int + * <li>xsd:unsignedByte --- short + * <li>xsd:time --- javax.xml.datatype.XMLGregorianCalendar + * <li>xsd:date --- javax.xml.datatype.XMLGregorianCalendar + * <li>xsd:g* --- javax.xml.datatype.XMLGregorianCalendar + * <li>xsd:anySimpleType (for xsd:element of this type)a + * java.lang.Object + * <li>xsd:anySimpleType (for xsd:attribute of this type) + * java.lang.String + * <li>xsd:duration javax.xml.datatype.Duration + * <li>xsd:NOTATION javax.xml.namespace.QName + * </ul> + */ + + if (literal == null) { + return null; + } + String value = literal.trim(); + + QName type = simpleType; + if (type.equals(XSD_STRING)) { + return parseString(value); + } else if (type.equals(XSD_INT)) { + return parseInt(value); + } else if (type.equals(XSD_INTEGER)) { + return parseInteger(value); + } else if (type.equals(XSD_INT)) { + return parseInt(value); + } else if (type.equals(XSD_FLOAT)) { + return parseFloat(value); + } else if (type.equals(XSD_DOUBLE)) { + return parseDouble(value); + } else if (type.equals(XSD_SHORT)) { + return parseShort(value); + } else if (type.equals(XSD_DECIMAL)) { + return parseDecimal(value); + } else if (type.equals(XSD_BOOLEAN)) { + return parseBoolean(value); + } else if (type.equals(XSD_BYTE)) { + return parseByte(value); + } else if (type.equals(XSD_LONG)) { + return parseLong(value); + } else if (type.equals(XSD_UNSIGNEDBYTE)) { + return parseUnsignedShort(value); + } else if (type.equals(XSD_UNSIGNEDSHORT)) { + return parseUnsignedShort(value); + } else if (type.equals(XSD_UNSIGNEDINT)) { + return parseUnsignedInt(value); + } else if (type.equals(XSD_UNSIGNEDLONG)) { + return parseUnsignedInt(value); + } else if (type.equals(XSD_DATETIME)) { + return parseDateTime(value); + } else if (type.equals(XSD_DATE)) { + return parseDate(value); + } else if (type.equals(XSD_TIME)) { + return parseTime(value); + } else if (type.equals(XSD_DURATION)) { + return parseDuration(value); + } else if (type.equals(XSD_HEXBIN)) { + return parseHexBinary(value); + } else if (type.equals(XSD_BASE64)) { + return parseBase64Binary(value); + } else if (type.equals(XSD_QNAME)) { + NamespaceContext namespaceContext = + (NamespaceContext)((context != null) ? context.getMetadata().get(NamespaceContext.class.getName()) : null); + return parseQName(value, namespaceContext); + } else if (type.equals(XSD_NOTATION)) { + NamespaceContext namespaceContext = + (NamespaceContext)((context != null) ? context.getMetadata().get(NamespaceContext.class.getName()) : null); + return parseQName(value, namespaceContext); + } else if (type.equals(XSD_YEAR)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_MONTH)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_DAY)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_YEARMONTH)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_MONTHDAY)) { + return factory.newXMLGregorianCalendar(value); + } else { + return value; + } + } + + @SuppressWarnings("deprecation") + private XMLGregorianCalendar toXMLGregorianCalendar(Date date) { + GregorianCalendar c = + new GregorianCalendar(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), + date.getSeconds()); + return factory.newXMLGregorianCalendar(c); + } + + private XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) { + return factory.newXMLGregorianCalendar(calendar); + } + + public String toXMLLiteral(QName simpleType, Object obj, TransformationContext context) { + if(obj == null) { + // It could be null if nilable=true + return null; + } + if (obj instanceof Float || obj instanceof Double) { + if (obj instanceof Float) { + return printDouble(((Float)obj).floatValue()); + } else { + return printDouble(((Double)obj).doubleValue()); + } + } else if (obj instanceof GregorianCalendar) { + GregorianCalendar calendar = (GregorianCalendar)obj; + return toXMLGregorianCalendar(calendar).toXMLFormat(); + } else if (obj instanceof Date) { + return toXMLGregorianCalendar((Date)obj).toXMLFormat(); + } else if (obj instanceof XMLGregorianCalendar) { + return ((XMLGregorianCalendar)obj).toXMLFormat(); + } else if (obj instanceof byte[]) { + if (simpleType != null) { + if (simpleType.equals(XSD_BASE64)) { + return printBase64Binary((byte[])obj); + } else if (simpleType.equals(XSD_HEXBIN)) { + return printHexBinary((byte[])obj); + } + } + } else if (obj instanceof QName) { + NamespaceContext namespaceContext = + (NamespaceContext)((context != null) ? context.getMetadata().get(NamespaceContext.class.getName()) : null); + return printQName((QName)obj, namespaceContext); + } + return obj.toString(); + } + + public static boolean isSimpleXSDType(QName typeName) { + if (typeName == null) { + return false; + } + return typeName.getNamespaceURI().equals(URI_2001_SCHEMA_XSD) + && XSD_SIMPLE_TYPES.get(typeName.getLocalPart()) != null; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java new file mode 100755 index 0000000000..058b037703 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +public class TransformationContextImpl implements TransformationContext { + private DataType sourceDataType; + + private DataType targetDataType; + + private final Map<String, Object> metadata = new HashMap<String, Object>(); + + private WeakReference<ClassLoader> classLoaderRef; + + public TransformationContextImpl() { + super(); + //FIXME The classloader should be passed in + setClassLoader(Thread.currentThread().getContextClassLoader()); + } + + public TransformationContextImpl(DataType sourceDataType, + DataType targetDataType, + ClassLoader classLoader, + Map<String, Object> metadata) { + super(); + this.sourceDataType = sourceDataType; + this.targetDataType = targetDataType; + setClassLoader(classLoader); + if (metadata != null) { + this.metadata.putAll(metadata); + } + } + + public DataType getSourceDataType() { + return sourceDataType; + } + + public DataType getTargetDataType() { + return targetDataType; + } + + public void setSourceDataType(DataType sourceDataType) { + this.sourceDataType = sourceDataType; + } + + public void setTargetDataType(DataType targetDataType) { + this.targetDataType = targetDataType; + } + + public final void setClassLoader(ClassLoader classLoader) { + this.classLoaderRef = new WeakReference<ClassLoader>(classLoader); + } + + public ClassLoader getClassLoader() { + return classLoaderRef.get(); + } + + public Map<String, Object> getMetadata() { + return metadata; + } + + /** + * @return the sourceOperation + */ + public Operation getSourceOperation() { + return (Operation) metadata.get("source.operation"); + } + + /** + * @param sourceOperation the sourceOperation to set + */ + public void setSourceOperation(Operation sourceOperation) { + this.metadata.put("source.operation", sourceOperation); + } + + /** + * @return the targetOperation + */ + public Operation getTargetOperation() { + return (Operation) metadata.get("target.operation"); + } + + /** + * @param targetOperation the targetOperation to set + */ + public void setTargetOperation(Operation targetOperation) { + this.metadata.put("target.operation", targetOperation); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java new file mode 100644 index 0000000000..310d1e6c00 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java @@ -0,0 +1,943 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.impl; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParsePosition; +import java.util.Calendar; +import java.util.TimeZone; + +import javax.xml.XMLConstants; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; + +/** + * Utility class for XSD data type conversions + */ +public class XSDDataTypeConverter { + public static final class Base64Binary { + private static final char[] S_BASE64CHAR = + {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', '+', '/'}; + + private static final char S_BASE64PAD = '='; + + private static final byte[] S_DECODETABLE = new byte[128]; + + static { + for (int i = 0; i < S_DECODETABLE.length; i++) { + S_DECODETABLE[i] = Byte.MAX_VALUE; // 127 + } + for (int i = 0; i < S_BASE64CHAR.length; i++) { + // 0 to 63 + S_DECODETABLE[S_BASE64CHAR[i]] = (byte) i; + } + } + + private Base64Binary() { + } + + /** + * + */ + public static byte[] decode(char[] data, int off, int len) { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[len / 4 * 3 + 3]; + int obufcount = 0; + for (int i = off; i < off + len; i++) { + char ch = data[i]; + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + obufcount += decode0(ibuf, obuf, obufcount); + } + } + } + if (obufcount == obuf.length) { + return obuf; + } + byte[] ret = new byte[obufcount]; + System.arraycopy(obuf, 0, ret, 0, obufcount); + return ret; + } + + /** + * + */ + public static void decode(char[] data, int off, int len, OutputStream ostream) throws IOException { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[3]; + for (int i = off; i < off + len; i++) { + char ch = data[i]; + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + int obufcount = decode0(ibuf, obuf, 0); + ostream.write(obuf, 0, obufcount); + } + } + } + } + + /** + * + */ + public static byte[] decode(String data) { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[data.length() / 4 * 3 + 3]; + int obufcount = 0; + for (int i = 0; i < data.length(); i++) { + char ch = data.charAt(i); + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + obufcount += decode0(ibuf, obuf, obufcount); + } + } + } + if (obufcount == obuf.length) { + return obuf; + } + byte[] ret = new byte[obufcount]; + System.arraycopy(obuf, 0, ret, 0, obufcount); + return ret; + } + + /** + * + */ + public static void decode(String data, OutputStream ostream) throws IOException { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[3]; + for (int i = 0; i < data.length(); i++) { + char ch = data.charAt(i); + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + int obufcount = decode0(ibuf, obuf, 0); + ostream.write(obuf, 0, obufcount); + } + } + } + } + + private static int decode0(char[] ibuf, byte[] obuf, int index) { + int wp = index; + int outlen = 3; + if (ibuf[3] == S_BASE64PAD) { + outlen = 2; + } + if (ibuf[2] == S_BASE64PAD) { + outlen = 1; + } + int b0 = S_DECODETABLE[ibuf[0]]; + int b1 = S_DECODETABLE[ibuf[1]]; + int b2 = S_DECODETABLE[ibuf[2]]; + int b3 = S_DECODETABLE[ibuf[3]]; + switch (outlen) { + case 1: + obuf[wp] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); + return 1; + case 2: + obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); + obuf[wp] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf); + return 2; + case 3: + obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); + obuf[wp++] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf); + obuf[wp] = (byte) (b2 << 6 & 0xc0 | b3 & 0x3f); + return 3; + default: + throw new IllegalArgumentException("The character sequence is not base64 encoded."); + } + } + + /** + * Returns base64 representation of specified byte array. + */ + public static String encode(byte[] data) { + return encode(data, 0, data.length); + } + + /** + * Returns base64 representation of specified byte array. + */ + public static String encode(byte[] data, int off, int len) { + if (len <= 0) { + return ""; + } + char[] out = new char[len / 3 * 4 + 4]; + int rindex = off; + int windex = 0; + int rest = len - off; + while (rest >= 3) { + int i = + ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + + (data[rindex + 2] & 0xff); + out[windex++] = S_BASE64CHAR[i >> 18]; + out[windex++] = S_BASE64CHAR[(i >> 12) & 0x3f]; + out[windex++] = S_BASE64CHAR[(i >> 6) & 0x3f]; + out[windex++] = S_BASE64CHAR[i & 0x3f]; + rindex += 3; + rest -= 3; + } + if (rest == 1) { + int i = data[rindex] & 0xff; + out[windex++] = S_BASE64CHAR[i >> 2]; + out[windex++] = S_BASE64CHAR[(i << 4) & 0x3f]; + out[windex++] = S_BASE64PAD; + out[windex++] = S_BASE64PAD; + } else if (rest == 2) { + int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff); + out[windex++] = S_BASE64CHAR[i >> 10]; + out[windex++] = S_BASE64CHAR[(i >> 4) & 0x3f]; + out[windex++] = S_BASE64CHAR[(i << 2) & 0x3f]; + out[windex++] = S_BASE64PAD; + } + return new String(out, 0, windex); + } + + /** + * Outputs base64 representation of the specified byte array to a byte stream. + */ + public static void encode(byte[] data, int off, int len, OutputStream ostream) throws IOException { + if (len <= 0) { + return; + } + byte[] out = new byte[4]; + int rindex = off; + int rest = len - off; + while (rest >= 3) { + int i = + ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + + (data[rindex + 2] & 0xff); + out[0] = (byte) S_BASE64CHAR[i >> 18]; + out[1] = (byte) S_BASE64CHAR[(i >> 12) & 0x3f]; + out[2] = (byte) S_BASE64CHAR[(i >> 6) & 0x3f]; + out[3] = (byte) S_BASE64CHAR[i & 0x3f]; + ostream.write(out, 0, 4); + rindex += 3; + rest -= 3; + } + if (rest == 1) { + int i = data[rindex] & 0xff; + out[0] = (byte) S_BASE64CHAR[i >> 2]; + out[1] = (byte) S_BASE64CHAR[(i << 4) & 0x3f]; + out[2] = (byte) S_BASE64PAD; + out[3] = (byte) S_BASE64PAD; + ostream.write(out, 0, 4); + } else if (rest == 2) { + int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff); + out[0] = (byte) S_BASE64CHAR[i >> 10]; + out[1] = (byte) S_BASE64CHAR[(i >> 4) & 0x3f]; + out[2] = (byte) S_BASE64CHAR[(i << 2) & 0x3f]; + out[3] = (byte) S_BASE64PAD; + ostream.write(out, 0, 4); + } + } + + /** + * Outputs base64 representation of the specified byte array to a character stream. + */ + public static void encode(byte[] data, int off, int len, Writer writer) throws IOException { + if (len <= 0) { + return; + } + char[] out = new char[4]; + int rindex = off; + int rest = len - off; + int output = 0; + while (rest >= 3) { + int i = + ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + + (data[rindex + 2] & 0xff); + out[0] = S_BASE64CHAR[i >> 18]; + out[1] = S_BASE64CHAR[(i >> 12) & 0x3f]; + out[2] = S_BASE64CHAR[(i >> 6) & 0x3f]; + out[3] = S_BASE64CHAR[i & 0x3f]; + writer.write(out, 0, 4); + rindex += 3; + rest -= 3; + output += 4; + if (output % 76 == 0) { + writer.write("\n"); + } + } + if (rest == 1) { + int i = data[rindex] & 0xff; + out[0] = S_BASE64CHAR[i >> 2]; + out[1] = S_BASE64CHAR[(i << 4) & 0x3f]; + out[2] = S_BASE64PAD; + out[3] = S_BASE64PAD; + writer.write(out, 0, 4); + } else if (rest == 2) { + int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff); + out[0] = S_BASE64CHAR[i >> 10]; + out[1] = S_BASE64CHAR[(i >> 4) & 0x3f]; + out[2] = S_BASE64CHAR[(i << 2) & 0x3f]; + out[3] = S_BASE64PAD; + writer.write(out, 0, 4); + } + } + } + + /** + * <p/> + * Utility class for xs:hexbinary. </p> + */ + public static final class HexBinary { + private HexBinary() { + } + + /** + * Converts the string <code>pValue</code> into an array of hex bytes. + */ + public static byte[] decode(String pValue) { + if ((pValue.length() % 2) != 0) { + throw new IllegalArgumentException("A HexBinary string must have even length."); + } + byte[] result = new byte[pValue.length() / 2]; + int j = 0; + int i = 0; + while (i < pValue.length()) { + byte b; + char c = pValue.charAt(i++); + char d = pValue.charAt(i++); + if (c >= '0' && c <= '9') { + b = (byte) ((c - '0') << 4); + } else if (c >= 'A' && c <= 'F') { + b = (byte) ((c - 'A' + 10) << 4); + } else if (c >= 'a' && c <= 'f') { + b = (byte) ((c - 'a' + 10) << 4); + } else { + throw new IllegalArgumentException("Invalid hex digit: " + c); + } + if (d >= '0' && d <= '9') { + b += (byte) (d - '0'); + } else if (d >= 'A' && d <= 'F') { + b += (byte) (d - 'A' + 10); + } else if (d >= 'a' && d <= 'f') { + b += (byte) (d - 'a' + 10); + } else { + throw new IllegalArgumentException("Invalid hex digit: " + d); + } + result[j++] = b; + } + return result; + } + + /** + * Converts the byte array <code>pHexBinary</code> into a string. + */ + public static String encode(byte[] pHexBinary) { + StringBuffer result = new StringBuffer(); + for (int i = 0; i < pHexBinary.length; i++) { + byte b = pHexBinary[i]; + byte c = (byte) ((b & 0xf0) >> 4); + if (c <= 9) { + result.append((char) ('0' + c)); + } else { + result.append((char) ('A' + c - 10)); + } + c = (byte) (b & 0x0f); + if (c <= 9) { + result.append((char) ('0' + c)); + } else { + result.append((char) ('A' + c - 10)); + } + } + return result.toString(); + } + + /** + * Creates a clone of the given byte array. + */ + public static byte[] getClone(byte[] pHexBinary) { + byte[] result = new byte[pHexBinary.length]; + System.arraycopy(pHexBinary, 0, result, 0, pHexBinary.length); + return result; + } + } + + public class XSDDateFormat extends XSDDateTimeFormat { + private static final long serialVersionUID = -1629412916827246627L; + + /** + * Creates a new instance. + */ + public XSDDateFormat() { + super(true, false); + } + } + + /** + * <p/> + * An instance of {@link java.text.Format}, which may be used to parse and format <code>xs:dateTime</code> values. + * </p> + */ + public static class XSDDateTimeFormat extends Format { + private static final long serialVersionUID = -1148332471737068969L; + + final boolean parseDate; + + final boolean parseTime; + + /** + * Creates a new instance. + */ + public XSDDateTimeFormat() { + this(true, true); + } + + XSDDateTimeFormat(boolean pParseDate, boolean pParseTime) { + parseDate = pParseDate; + parseTime = pParseTime; + } + + private void append(StringBuffer pBuffer, int pNum, int pMinLen) { + String s = Integer.toString(pNum); + for (int i = s.length(); i < pMinLen; i++) { + pBuffer.append('0'); + } + pBuffer.append(s); + } + + @Override + public StringBuffer format(Object pCalendar, StringBuffer pBuffer, FieldPosition pPos) { + assert pCalendar != null : "The Calendar argument must not be null."; + assert pBuffer != null : "The StringBuffer argument must not be null."; + assert pPos != null : "The FieldPosition argument must not be null."; + + Calendar cal = (Calendar) pCalendar; + if (parseDate) { + int year = cal.get(Calendar.YEAR); + if (year < 0) { + pBuffer.append('-'); + year = -year; + } + append(pBuffer, year, 4); + pBuffer.append('-'); + append(pBuffer, cal.get(Calendar.MONTH) + 1, 2); + pBuffer.append('-'); + append(pBuffer, cal.get(Calendar.DAY_OF_MONTH), 2); + if (parseTime) { + pBuffer.append('T'); + } + } + if (parseTime) { + append(pBuffer, cal.get(Calendar.HOUR_OF_DAY), 2); + pBuffer.append(':'); + append(pBuffer, cal.get(Calendar.MINUTE), 2); + pBuffer.append(':'); + append(pBuffer, cal.get(Calendar.SECOND), 2); + int millis = cal.get(Calendar.MILLISECOND); + if (millis > 0) { + pBuffer.append('.'); + append(pBuffer, millis, 3); + } + } + TimeZone tz = cal.getTimeZone(); + // JDK 1.4: int offset = tz.getOffset(cal.getTimeInMillis()); + int offset = cal.get(Calendar.ZONE_OFFSET); + if (tz.inDaylightTime(cal.getTime())) { + offset += cal.get(Calendar.DST_OFFSET); + } + if (offset == 0) { + pBuffer.append('Z'); + } else { + if (offset < 0) { + pBuffer.append('-'); + offset = -offset; + } else { + pBuffer.append('+'); + } + int minutes = offset / (60 * 1000); + int hours = minutes / 60; + minutes -= hours * 60; + append(pBuffer, hours, 2); + pBuffer.append(':'); + append(pBuffer, minutes, 2); + } + return pBuffer; + } + + private int parseInt(String pString, int offset, StringBuffer pDigits) { + int length = pString.length(); + int pOffset = offset; + pDigits.setLength(0); + while (pOffset < length) { + char c = pString.charAt(pOffset); + if (Character.isDigit(c)) { + pDigits.append(c); + ++pOffset; + } else { + break; + } + } + return pOffset; + } + + @Override + public Object parseObject(String pString, ParsePosition pParsePosition) { + assert pString != null : "The String argument must not be null."; + assert pParsePosition != null : "The ParsePosition argument must not be null."; + int offset = pParsePosition.getIndex(); + int length = pString.length(); + + boolean isMinus = false; + StringBuffer digits = new StringBuffer(); + int year = 0; + int month = 0; + int mday = 0; + if (parseDate) { + // Sign + if (offset < length) { + char c = pString.charAt(offset); + if (c == '+') { + ++offset; + } else if (c == '-') { + ++offset; + isMinus = true; + } + } + + offset = parseInt(pString, offset, digits); + if (digits.length() < 4) { + pParsePosition.setErrorIndex(offset); + return null; + } + year = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == '-') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + month = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == '-') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + mday = Integer.parseInt(digits.toString()); + + if (parseTime) { + if (offset < length && pString.charAt(offset) == 'T') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + } + } else { + year = month = mday = 0; + } + + int hour = 0; + int minute = 0; + int second = 0; + int millis = 0; + if (parseTime) { + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + hour = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == ':') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + minute = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == ':') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + second = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == '.') { + ++offset; + offset = parseInt(pString, offset, digits); + if (digits.length() > 0) { + millis = Integer.parseInt(digits.toString()); + } else { + millis = 0; + } + } else { + millis = 0; + } + } else { + hour = minute = second = millis = 0; + } + + digits.setLength(0); + digits.append("GMT"); + if (offset < length) { + char c = pString.charAt(offset); + if (c == 'Z') { + // Ignore UTC, it is the default + ++offset; + } else if (c == '+' || c == '-') { + digits.append(c); + ++offset; + for (int i = 0; i < 5; i++) { + if (offset >= length) { + pParsePosition.setErrorIndex(offset); + return null; + } + c = pString.charAt(offset); + if ((i != 2 && Character.isDigit(c)) || (i == 2 && c == ':')) { + digits.append(c); + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + ++offset; + } + } + } + + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(digits.toString())); + cal.set(isMinus ? -year : year, parseDate ? month - 1 : month, mday, hour, minute, second); + cal.set(Calendar.MILLISECOND, millis); + pParsePosition.setIndex(offset); + return cal; + } + } + + public static class XSDTimeFormat extends XSDDateTimeFormat { + private static final long serialVersionUID = 1346506860724640517L; + + /** + * Creates a new instance. + */ + public XSDTimeFormat() { + super(false, true); + } + } + + private static final long MAX_UNSIGNED_INT = (((long) Integer.MAX_VALUE) * 2) + 1; + + private static final int MAX_UNSIGNED_SHORT = Short.MAX_VALUE * 2 + 1; + + public String parseAnySimpleType(String value) { + return value; + } + + public byte[] parseBase64Binary(String value) { + return Base64Binary.decode(value); + } + + public boolean parseBoolean(String value) { + return Boolean.valueOf(value).booleanValue(); + } + + public byte parseByte(String value) { + return Byte.parseByte(value); + } + + public Calendar parseDate(String value) { + XSDDateFormat format = new XSDDateFormat(); + ParsePosition pos = new ParsePosition(0); + Calendar cal = (Calendar) format.parseObject(value, pos); + if (cal == null) { + throw new IllegalArgumentException("Failed to parse date " + value + " at:" + + value.substring(pos.getErrorIndex())); + } + return cal; + } + + public Calendar parseDateTime(String value) { + XSDDateTimeFormat format = new XSDDateTimeFormat(); + ParsePosition pos = new ParsePosition(0); + Calendar cal = (Calendar) format.parseObject(value, pos); + if (cal == null) { + throw new IllegalArgumentException("Failed to parse dateTime " + value + " at:" + + value.substring(pos.getErrorIndex())); + } + return cal; + } + + public BigDecimal parseDecimal(String value) { + return new BigDecimal(value); + } + + public double parseDouble(String value) { + if ("INF".equals(value)) { + return Double.POSITIVE_INFINITY; + } else if ("-INF".equals(value)) { + return Double.NEGATIVE_INFINITY; + } else if ("NaN".equals(value)) { + return Double.NaN; + } else { + return Double.parseDouble(value); + } + } + + public Duration parseDuration(String pDuration) { + try { + return DatatypeFactory.newInstance().newDuration(pDuration); + } catch (DatatypeConfigurationException e) { + throw new IllegalArgumentException(e); + } + } + + public float parseFloat(String value) { + if ("INF".equals(value)) { + return Float.POSITIVE_INFINITY; + } else if ("-INF".equals(value)) { + return Float.NEGATIVE_INFINITY; + } else if ("NaN".equals(value)) { + return Float.NaN; + } else { + return Float.parseFloat(value); + } + } + + public byte[] parseHexBinary(String value) { + return HexBinary.decode(value); + } + + public int parseInt(String value) { + return Integer.parseInt(value); + } + + public BigInteger parseInteger(String value) { + return new BigInteger(value); + } + + public long parseLong(String value) { + return Long.parseLong(value); + } + + public QName parseQName(String value, NamespaceContext context) { + int offset = value.indexOf(':'); + String uri; + String localName; + switch (offset) { + case -1: + localName = value; + uri = context.getNamespaceURI(""); + if (uri == null) { + // Should not happen, indicates an error in the + // NamespaceContext + // implementation + throw new IllegalArgumentException("The default prefix is not bound."); + } + break; + case 0: + throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + + value); + default: + String prefix = value.substring(0, offset); + localName = value.substring(offset + 1); + uri = context.getNamespaceURI(prefix); + if (uri == null) { + throw new IllegalArgumentException("The prefix " + prefix + " is not bound."); + } + } + return new QName(uri, localName); + } + + public short parseShort(String value) { + return Short.parseShort(value); + } + + public String parseString(String value) { + return value; + } + + public Calendar parseTime(String value) { + XSDTimeFormat format = new XSDTimeFormat(); + ParsePosition pos = new ParsePosition(0); + Calendar cal = (Calendar) format.parseObject(value, pos); + if (cal == null) { + throw new IllegalArgumentException("Failed to parse time " + value + " at:" + + value.substring(pos.getErrorIndex())); + } + return cal; + } + + public long parseUnsignedInt(String value) { + long l = Long.parseLong(value); + if (l < 0) { + throw new IllegalArgumentException("Failed to parse UnsignedInt " + value + + ": result is negative"); + } + if (l > MAX_UNSIGNED_INT) { + throw new IllegalArgumentException("Failed to parse UnsignedInt " + value + + ": result exceeds maximum value " + MAX_UNSIGNED_INT); + } + return l; + } + + public int parseUnsignedShort(String value) { + int i = Integer.parseInt(value); + if (i < 0) { + throw new IllegalArgumentException("Failed to parse UnsignedShort " + value + + ": result is negative"); + } + if (i > MAX_UNSIGNED_SHORT) { + throw new IllegalArgumentException("Failed to parse UnsignedShort " + value + + ": result exceeds maximum value " + MAX_UNSIGNED_SHORT); + } + return i; + } + + public String printAnySimpleType(String value) { + return value; + } + + public String printBase64Binary(byte[] value) { + return Base64Binary.encode(value); + } + + public String printBoolean(boolean value) { + return (value ? Boolean.TRUE : Boolean.FALSE).toString(); + } + + public String printByte(byte value) { + return Byte.toString(value); + } + + public String printDate(Calendar value) { + return new XSDDateFormat().format(value); + } + + public String printDateTime(Calendar value) { + return new XSDDateTimeFormat().format(value); + } + + public String printDecimal(BigDecimal value) { + return value.toString(); + } + + public String printDouble(double value) { + return Double.toString(value); + } + + public String printDuration(Duration pDuration) { + return pDuration.toString(); + } + + public String printFloat(float value) { + return Float.toString(value); + } + + public String printHexBinary(byte[] value) { + return HexBinary.encode(value); + } + + public String printInt(int value) { + return Integer.toString(value); + } + + public String printInteger(BigInteger value) { + return value.toString(); + } + + public String printLong(long value) { + return Long.toString(value); + } + + public String printQName(QName value, NamespaceContext context) { + String prefix = context.getPrefix(value.getNamespaceURI()); + if (prefix == null) { + throw new IllegalArgumentException("The namespace URI " + value.getNamespaceURI() + + " is not bound."); + } else if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { + return value.getLocalPart(); + } else { + return prefix + ":" + value.getLocalPart(); + } + } + + public String printShort(short value) { + return Short.toString(value); + } + + public String printString(String value) { + return value; + } + + public String printTime(Calendar value) { + return new XSDTimeFormat().format(value); + } + + public String printUnsignedInt(long value) { + return Long.toString(value); + } + + public String printUnsignedShort(int value) { + return Integer.toString(value); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.java new file mode 100644 index 0000000000..31a36f6fdd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.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.tuscany.sca.databinding.javabeans;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Transformer to convert data from DOM Node to JavaBean
+ */
+public class DOMNode2JavaBeanTransformer extends XML2JavaBeanTransformer<Node> {
+
+ @Override
+ public Node getRootElement(Node element) throws XML2JavaMapperException {
+ if (element instanceof Document) {
+ return ((Document)element).getDocumentElement();
+ } else {
+ return element;
+ }
+
+ }
+
+ @Override
+ public List<Node> getChildElements(Node parent) throws XML2JavaMapperException {
+ NodeList nodeList = parent.getChildNodes();
+ List<Node> nodeArrayList = new ArrayList<Node>(nodeList.getLength());
+ for (int count = 0; count < nodeList.getLength(); ++count) {
+ nodeArrayList.add(nodeList.item(count));
+ }
+
+ return nodeArrayList;
+ }
+
+ @Override
+ public String getElementName(Node element) throws XML2JavaMapperException {
+ return element.getLocalName();
+ }
+
+ @Override
+ public String getText(Node element) throws XML2JavaMapperException {
+ if (element instanceof Document) {
+ element = ((Document)element).getDocumentElement();
+ }
+ return element.getTextContent();
+ }
+
+ @Override
+ public boolean isTextElement(Node element) throws XML2JavaMapperException {
+ return element.getNodeType() == Node.TEXT_NODE;
+ }
+
+ @Override
+ public Class getSourceType() {
+ return Node.class;
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.java new file mode 100644 index 0000000000..050c4288c3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.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.tuscany.sca.databinding.javabeans;
+
+import javax.xml.namespace.QName;
+
+/**
+ * This exception is used to encapsulate and rethrow exceptions that arise out
+ * of converting JavaBean objects to XML
+ */
+public class Java2XMLMapperException extends RuntimeException {
+ private static final long serialVersionUID = 6811924384399578686L;
+
+ private QName xmlElementName;
+ private String javaFieldName;
+ private Class javaType;
+
+ public Java2XMLMapperException(String message) {
+ super(message);
+ }
+
+ public Java2XMLMapperException(Throwable cause) {
+ super(cause);
+ }
+
+ public String getJavaFieldName() {
+ return javaFieldName;
+ }
+
+ public void setJavaFieldName(String javaFieldName) {
+ this.javaFieldName = javaFieldName;
+ }
+
+ public Class getJavaType() {
+ return javaType;
+ }
+
+ public void setJavaType(Class javaType) {
+ this.javaType = javaType;
+ }
+
+ public QName getXmlElementName() {
+ return xmlElementName;
+ }
+
+ public void setXmlElementName(QName xmlElementName) {
+ this.xmlElementName = xmlElementName;
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.java new file mode 100644 index 0000000000..056eea58d6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.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.tuscany.sca.databinding.javabeans;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.tuscany.sca.databinding.impl.DOMHelper;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+
+/**
+ * Transformer to convert data from a JavaBean object to DOM Node
+ */
+public class JavaBean2DOMNodeTransformer extends JavaBean2XMLTransformer<Node> {
+
+ public static final String COLON = ":";
+ private Document factory;
+
+ public JavaBean2DOMNodeTransformer() {
+ super();
+ try {
+ factory = DOMHelper.newDocument();
+ } catch (ParserConfigurationException e) {
+ throw new Java2XMLMapperException(e);
+ }
+ }
+
+ @Override
+ public void appendChild(Node parentElement, Node childElement) throws Java2XMLMapperException {
+ parentElement.appendChild(childElement);
+ }
+
+ @Override
+ public Node createElement(QName qName) throws Java2XMLMapperException {
+ String qualifedName =
+ (qName.getPrefix() == null || qName.getPrefix().length() <= 0) ? qName.getLocalPart()
+ : qName.getPrefix() + COLON + qName.getLocalPart();
+ return factory.createElementNS(qName.getNamespaceURI(), qualifedName);
+ }
+
+ @Override
+ public Node createText(String textData) throws Java2XMLMapperException {
+ if (textData != null) {
+ return factory.createTextNode(textData);
+ } else {
+ Attr nil = factory.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil");
+ nil.setValue("true");
+ return nil;
+ }
+ }
+
+ @Override
+ public Class getTargetType() {
+ return Node.class;
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReader.java new file mode 100644 index 0000000000..a0a9493551 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReader.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.tuscany.sca.databinding.javabeans; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.xml.BeanUtil; +import org.apache.tuscany.sca.databinding.xml.XMLDocumentStreamReader; + +public class JavaBean2XMLStreamReader extends BaseTransformer<Object, XMLStreamReader> implements + PullTransformer<Object, XMLStreamReader> { + + public XMLStreamReader transform(Object source, TransformationContext context) { + try { + return new XMLDocumentStreamReader(BeanUtil.getXMLStreamReader(source)); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Object.class; + } + + @Override + public Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java new file mode 100644 index 0000000000..1f64a6aa82 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java @@ -0,0 +1,228 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.databinding.javabeans;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Date;
+import java.util.GregorianCalendar;
+
+import javax.xml.datatype.XMLGregorianCalendar;
+import javax.xml.namespace.QName;
+
+import org.apache.tuscany.sca.databinding.PullTransformer;
+import org.apache.tuscany.sca.databinding.TransformationContext;
+import org.apache.tuscany.sca.databinding.impl.BaseTransformer;
+import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl;
+
+/**
+ * Transformer to convert data from a JavaBean object to xml
+ */
+public abstract class JavaBean2XMLTransformer<T> extends BaseTransformer<Object, T> implements
+ PullTransformer<Object, T> {
+
+ public static final String GET = "get";
+ public static final String PREFIX = "n";
+ public static final String PERIOD = ".";
+ public static final String FWD_SLASH = "/";
+ public static final String HTTP = "http://";
+ private static int prefixCount = 1;
+
+ protected SimpleTypeMapperImpl mapper;
+
+ public JavaBean2XMLTransformer() {
+ this.mapper = new SimpleTypeMapperImpl();
+ }
+
+ public T transform(Object source, TransformationContext context) {
+
+ //FIXME See how/if we still need to get the metadata here
+ //QName rootElementName = (QName)context.getTargetDataType().getMetadata("RootElementName");
+ //if (rootElementName == null) {
+ QName rootElementName = new QName(resolveRootElementName(source.getClass()));
+ //}
+
+ T root = createElement(rootElementName);
+ appendChildElements(root,
+ resolveElementName(source.getClass()),
+ source.getClass(),
+ source,
+ context);
+ return root;
+ }
+
+ private void appendChildElements(T parent,
+ QName elementName,
+ Class javaType,
+ Object javaObject,
+ TransformationContext context) {
+ T element = null;
+ if (javaObject != null) {
+ if (javaType.isPrimitive() || isSimpleJavaType(javaObject)) {
+ appendChild(parent, createText(mapper.toXMLLiteral(null, javaObject, context)));
+ } else if (javaType.isArray()) {
+ boolean arrayDone = false;
+ Object arrayObject = null;
+ for (int count = 0; !arrayDone; ++count) {
+ try {
+ arrayObject = Array.get(javaObject, count);
+ element = createElement(elementName);
+ appendChild(parent, element);
+ appendChildElements(element,
+ elementName,
+ javaType.getComponentType(),
+ arrayObject,
+ context);
+ } catch (ArrayIndexOutOfBoundsException e1) {
+ arrayDone = true;
+ }
+ }
+ } else {
+ Field[] javaFields = javaType.getFields();
+ for (Field aField : javaFields) {
+ try {
+ QName fieldElementName = new QName(aField.getName());
+ if (!aField.getType().isArray()) {
+ element = createElement(fieldElementName);
+ appendChild(parent, element);
+ appendChildElements(element,
+ fieldElementName,
+ aField.getType(),
+ aField.get(javaObject),
+ context);
+ } else {
+ appendChildElements(parent,
+ fieldElementName,
+ aField.getType(),
+ aField.get(javaObject),
+ context);
+ }
+ } catch (IllegalAccessException e) {
+ Java2XMLMapperException java2xmlEx = new Java2XMLMapperException(e);
+ java2xmlEx.setJavaFieldName(aField.getName());
+ java2xmlEx.setJavaType(javaType);
+ throw java2xmlEx;
+ }
+ }
+
+ Method[] methods = javaType.getDeclaredMethods();
+ String fieldName = null;
+ for (Method aMethod : methods) {
+ try {
+ if (Modifier.isPublic(aMethod.getModifiers()) && aMethod.getName().startsWith(GET)
+ && aMethod.getParameterTypes().length == 0) {
+ fieldName = resolveFieldFromMethod(aMethod.getName());
+ try {
+ javaType.getField(fieldName);
+ } catch (NoSuchFieldException e) {
+ QName fieldElementName = new QName(fieldName);
+ if (aMethod.getReturnType().isArray()) {
+ appendChildElements(parent, fieldElementName, aMethod.getReturnType(), aMethod
+ .invoke(javaObject, new Object[0]), context);
+ } else {
+ element = createElement(fieldElementName);
+ appendChild(parent, element);
+ appendChildElements(element, fieldElementName, aMethod.getReturnType(), aMethod
+ .invoke(javaObject, new Object[0]), context);
+ }
+ }
+ }
+ } catch (IllegalAccessException e) {
+ Java2XMLMapperException java2xmlEx = new Java2XMLMapperException(e);
+ java2xmlEx.setJavaFieldName(fieldName);
+ java2xmlEx.setJavaType(javaType);
+ throw java2xmlEx;
+ } catch (InvocationTargetException e) {
+ Java2XMLMapperException java2xmlEx = new Java2XMLMapperException(e);
+ java2xmlEx.setJavaFieldName(fieldName);
+ java2xmlEx.setJavaType(javaType);
+ throw java2xmlEx;
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public Class getSourceType() {
+ return Object.class;
+ }
+
+ private boolean isSimpleJavaType(Object javaObject) {
+ if (javaObject instanceof String) {
+ return true;
+ }
+ if (javaObject instanceof Byte || javaObject instanceof Character
+ || javaObject instanceof Short
+ || javaObject instanceof Integer
+ || javaObject instanceof Long
+ || javaObject instanceof Float
+ || javaObject instanceof Double
+ || javaObject instanceof Boolean) {
+ return true;
+ }
+ if (javaObject instanceof GregorianCalendar || javaObject instanceof Date
+ || javaObject instanceof XMLGregorianCalendar
+ || javaObject instanceof byte[]
+ || javaObject instanceof QName) {
+ return true;
+ }
+ return false;
+ }
+
+ private String resolveRootElementName(Class javaType) {
+ if (javaType.isArray()) {
+ return javaType.getComponentType().getSimpleName() + "_collection";
+ } else {
+ return javaType.getSimpleName() + "_instance";
+ }
+ }
+
+
+ private QName resolveElementName(Class javaType) {
+ if (javaType.isArray()) {
+ return new QName(javaType.getComponentType().getSimpleName());
+ } else {
+ return new QName(javaType.getSimpleName());
+ }
+ }
+
+ private String resolveFieldFromMethod(String methodName) {
+ StringBuffer fieldName = new StringBuffer();
+ fieldName.append(Character.toLowerCase(methodName.charAt(GET.length())));
+ fieldName.append(methodName.substring(GET.length() + 1));
+ return fieldName.toString();
+ }
+
+ public String getNexPrefix() {
+ return PREFIX + prefixCount++;
+ }
+
+ @Override
+ public int getWeight() {
+ return JavaBeansDataBinding.HEAVY_WEIGHT;
+ }
+
+ public abstract T createElement(QName qName) throws Java2XMLMapperException;
+ public abstract T createText(String textData) throws Java2XMLMapperException;
+ public abstract void appendChild(T parentElement, T childElement) throws Java2XMLMapperException;
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.java new file mode 100644 index 0000000000..f7b684e227 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.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.tuscany.sca.databinding.javabeans;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.OutputStream;
+import java.io.Serializable;
+
+import org.apache.tuscany.sca.databinding.ExceptionHandler;
+import org.apache.tuscany.sca.databinding.impl.BaseDataBinding;
+
+/**
+ * DataBinding for JavaBeans
+ */
+public class JavaBeansDataBinding extends BaseDataBinding {
+ /**
+ * Defining a weight to a very high number so that the transformer won't be picked
+ * up by other paths unless it's the only available path
+ */
+ public static final int HEAVY_WEIGHT = 10000;
+ public static final String NAME = Object.class.getName();
+
+ public JavaBeansDataBinding() {
+ super(NAME, Object.class);
+ }
+
+ @Override
+ public Object copy(Object arg) {
+ if (arg == null) {
+ return null;
+ }
+ final Class clazz = arg.getClass();
+ if (String.class == clazz || clazz.isPrimitive()
+ || Number.class.isAssignableFrom(clazz)
+ || Boolean.class.isAssignableFrom(clazz)
+ || Character.class.isAssignableFrom(clazz)
+ || Byte.class.isAssignableFrom(clazz)) {
+ // Immutable classes
+ return arg;
+ }
+ try {
+ if (arg instanceof Serializable) {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = getObjectOutputStream(bos);
+ oos.writeObject(arg);
+ oos.close();
+ bos.close();
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
+ ObjectInputStream ois = getObjectInputStream(bis, clazz.getClassLoader());
+ Object objectCopy = ois.readObject();
+ ois.close();
+ bis.close();
+ return objectCopy;
+ } else {
+ // return arg;
+ throw new IllegalArgumentException("Argument type '" + arg.getClass().getCanonicalName() + "' is not Serializable. " +
+ " Pass-by-value cannot be performed on this argument");
+ }
+ } catch (Exception e) {
+ throw new IllegalArgumentException("Pass-by-value is not supported for the given object", e);
+ }
+ }
+
+ @Override
+ public ExceptionHandler getExceptionHandler() {
+ return new JavaBeansExceptionHandler();
+ }
+
+ protected ObjectOutputStream getObjectOutputStream(OutputStream os) throws IOException {
+ return new ObjectOutputStream(os);
+ }
+
+ protected ObjectInputStream getObjectInputStream(InputStream is, final ClassLoader cl) throws IOException {
+ ObjectInputStream ois = new ObjectInputStream(is) {
+ @Override
+ protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
+ try {
+ return Class.forName(desc.getName(), false, cl);
+ } catch (ClassNotFoundException e) {
+ return super.resolveClass(desc);
+ }
+ }
+
+ };
+ return ois;
+ }
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansExceptionHandler.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansExceptionHandler.java new file mode 100644 index 0000000000..8c704b6df2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansExceptionHandler.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.tuscany.sca.databinding.javabeans; + +import org.apache.tuscany.sca.databinding.ExceptionHandler; +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * Simple excecption handler for the JavaBeans data binding. + */ +public class JavaBeansExceptionHandler implements ExceptionHandler { + + public Exception createException(DataType<DataType> exceptionType, String message, Object faultInfo, Throwable cause) { + if (faultInfo instanceof Exception) { + return (Exception)faultInfo; + } + return null; + } + + public Object getFaultInfo(Exception exception) { + return exception; + } + + public DataType<?> getFaultType(DataType exceptionDataType) { + // We only handle faults that have been explicitly associated with the + // JavaBeansDataBinding by the DefaultDataBindingExtensionPoint. + if (JavaBeansDataBinding.NAME.equals(exceptionDataType.getDataBinding())) { + return exceptionDataType; + } + return null; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.java new file mode 100644 index 0000000000..1fe75f1de9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.javabeans; + +import java.lang.annotation.Annotation; + +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.databinding.xml.XMLStringDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * DataBinding for Java simple types + */ +public class SimpleJavaDataBinding extends BaseDataBinding { + public static final String NAME = "java:simpleType"; + + public SimpleJavaDataBinding() { + super(NAME, Object.class); + } + + @Override + public Object copy(Object arg) { + return arg; + } + + @Override + public boolean introspect(DataType type, Annotation[] annotations) { + Class<?> cls = type.getPhysical(); + if (cls == Object.class) { + return false; + } + // HACK: [rfeng] By pass the one know to XMLString + String db = type.getDataBinding(); + if (db != null && (XMLStringDataBinding.NAME.equals(db) || XMLStringDataBinding.ALIASES[0].equals(db))) { + return false; + } + if (SimpleTypeMapperImpl.JAVA2XML.keySet().contains(cls)) { + type.setDataBinding(getName()); + type.setLogical(new XMLType(SimpleTypeMapperImpl.getXMLType(cls))); + return true; + } else { + return false; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java new file mode 100644 index 0000000000..76f51c4ef0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java @@ -0,0 +1,296 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tuscany.sca.databinding.javabeans;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+
+import org.apache.tuscany.sca.databinding.PullTransformer;
+import org.apache.tuscany.sca.databinding.TransformationContext;
+import org.apache.tuscany.sca.databinding.impl.BaseTransformer;
+import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl;
+import org.apache.tuscany.sca.interfacedef.util.XMLType;
+
+/**
+ * Transformer to convert data from XML to JavaBean
+ */
+public abstract class XML2JavaBeanTransformer<T> extends BaseTransformer<T, Object> implements
+ PullTransformer<T, Object> {
+
+ public static final String SET = "set";
+
+ protected SimpleTypeMapperImpl mapper;
+
+ public XML2JavaBeanTransformer() {
+ this.mapper = new SimpleTypeMapperImpl();
+ }
+
+ @Override
+ public int getWeight() {
+ return JavaBeansDataBinding.HEAVY_WEIGHT;
+ }
+
+ public Object transform(T source, TransformationContext context) {
+ XMLType xmlType = (XMLType) context.getSourceDataType().getLogical();
+ return toJavaObject(xmlType.getTypeName(), getRootElement(source), context);
+ }
+
+ public Object toJavaObject(QName xmlType, T xmlElement, TransformationContext context) {
+ if (SimpleTypeMapperImpl.isSimpleXSDType(xmlType)) {
+ return mapper.toJavaObject(xmlType, getText(xmlElement), context);
+ } else {
+ Class<?> javaType = (Class<?>)context.getTargetDataType().getPhysical();
+ return createJavaObject(xmlElement, javaType, context);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private <L> L createJavaObject(T element, Class<L> javaType, TransformationContext context)
+ throws XML2JavaMapperException {
+ List<T> childElements = getChildElements(element);
+ if (childElements.size() == 1 && isTextElement(childElements.get(0))) {
+ return (L) mapper.toJavaObject(mapper.getXMLType(javaType).getQName(),
+ getText(childElements.get(0)),
+ context);
+ } else {
+ String fieldName = null;
+ try {
+ L javaInstance = javaType.newInstance();
+ Map<Field, List<Object>> arrayFields = new Hashtable<Field, List<Object>>();
+ Map<Method, List<Object>> arraySetters = new Hashtable<Method, List<Object>>();
+ for (int count = 0; count < childElements.size(); ++count) {
+ if (!isTextElement(childElements.get(count))) {
+ fieldName = getElementName(childElements.get(count));
+ try {
+ Field javaField = javaType.getField(fieldName);
+ setFieldValue(javaInstance,
+ javaField,
+ childElements.get(count),
+ arrayFields,
+ context);
+
+ } catch (NoSuchFieldException e1) {
+ setFieldValueUsingSetter(javaType,
+ javaInstance,
+ fieldName,
+ childElements.get(count),
+ arraySetters,
+ context);
+ }
+ }
+ }
+
+ setArrayValues(javaInstance, arrayFields, arraySetters);
+ return javaInstance;
+ } catch (Exception e2) {
+ XML2JavaMapperException xml2JavaEx = new XML2JavaMapperException(e2);
+ xml2JavaEx.setJavaType(javaType);
+ xml2JavaEx.setJavaFieldName(fieldName);
+ throw xml2JavaEx;
+ }
+ }
+ }
+
+ private void setFieldValue(Object javaInstance,
+ Field javaField,
+ T fieldValue,
+ Map<Field, List<Object>> arrayFields,
+ TransformationContext context) throws IllegalAccessException {
+ Class<?> javaFieldType = (Class<?>) javaField.getType();
+
+ if (javaFieldType.isArray()) {
+ Class<?> componentType = javaFieldType.getComponentType();
+ List<Object> fldValueArray = arrayFields.get(javaField);
+ if (fldValueArray == null) {
+ fldValueArray = new ArrayList<Object>();
+ arrayFields.put(javaField, fldValueArray);
+ }
+ fldValueArray.add(createJavaObject(fieldValue, componentType, context));
+ } else {
+ javaField.setAccessible(true);
+ javaField.set(javaInstance, createJavaObject(fieldValue, javaFieldType, context));
+ }
+ }
+
+ private void setFieldValueUsingSetter(Class javaType,
+ Object javaInstance,
+ String fieldName,
+ T fieldValue,
+ Map<Method, List<Object>> arraySetters,
+ TransformationContext context) throws IllegalAccessException,
+ InvocationTargetException {
+ char firstChar = Character.toUpperCase(fieldName.charAt(0));
+ StringBuilder methodName = new StringBuilder(SET + fieldName);
+ methodName.setCharAt(SET.length(), firstChar);
+ boolean methodNotFound = true;
+
+ for (int methodCount = 0; methodNotFound && methodCount < javaType.getMethods().length; ++methodCount) {
+ Method aMethod = javaType.getMethods()[methodCount];
+ if (aMethod.getName().equals(methodName.toString())
+ && aMethod.getParameterTypes().length == 1) {
+ Class<?> paramType = aMethod.getParameterTypes()[0];
+
+ if (paramType.isArray()) {
+ Class<?> componentType = paramType.getComponentType();
+ List<Object> setterValueArray = arraySetters.get(aMethod);
+ if (setterValueArray == null) {
+ setterValueArray = new ArrayList<Object>();
+ arraySetters.put(aMethod, setterValueArray);
+ }
+ setterValueArray.add(createJavaObject(fieldValue, componentType, context));
+ } else {
+ aMethod.invoke(javaInstance, new Object[] {createJavaObject(fieldValue,
+ paramType,
+ context)});
+ }
+ methodNotFound = false;
+ }
+ }
+
+ if (methodNotFound) {
+ XML2JavaMapperException xml2JavaEx =
+ new XML2JavaMapperException("No field or setter method to configure xml data");
+ xml2JavaEx.setJavaFieldName(fieldName);
+ xml2JavaEx.setJavaType(javaType);
+ throw xml2JavaEx;
+ }
+ }
+
+ private void setArrayValues(Object javaInstance,
+ Map<Field, List<Object>> arrayFields,
+ Map<Method, List<Object>> arraySetters) throws IllegalAccessException,
+ InvocationTargetException {
+ if (arrayFields.size() > 0) {
+ for (Field javaField : arrayFields.keySet()) {
+ javaField.setAccessible(true);
+
+ if (javaField.getType().getComponentType().isPrimitive()) {
+ javaField.set(javaInstance, createPrimitiveArray(javaField.getType()
+ .getComponentType(),
+ arrayFields.get(javaField)));
+ } else {
+ javaField.set(javaInstance,
+ createNonPrimitiveArray(javaField.getType().getComponentType(),
+ arrayFields.get(javaField)));
+ }
+ }
+ }
+
+ if (arraySetters.size() > 0) {
+ for (Method aMethod : arraySetters.keySet()) {
+ Class paramType = aMethod.getParameterTypes()[0];
+ if (paramType.getComponentType().isPrimitive()) {
+ aMethod.invoke(javaInstance,
+ new Object[] {createPrimitiveArray(paramType.getComponentType(),
+ arraySetters.get(aMethod))});
+ } else {
+ aMethod.invoke(javaInstance,
+ new Object[] {createNonPrimitiveArray(paramType.getComponentType(),
+ arraySetters.get(aMethod))});
+ }
+ }
+ }
+ }
+
+ private Object createNonPrimitiveArray(Class fieldType, List values) {
+ Object objectArray = Array.newInstance(fieldType, values.size());
+ for (int count = 0; count < values.size(); ++count) {
+ Array.set(objectArray, count, values.get(count));
+ }
+ return objectArray;
+ }
+
+ private Object createPrimitiveArray(Class fieldType, List values) {
+ if (fieldType.isPrimitive()) {
+ if (fieldType.getName().equals("int")) {
+ int[] primitiveValues = new int[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Integer) values.get(count)).intValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("float")) {
+ float[] primitiveValues = new float[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Float) values.get(count)).floatValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("boolean")) {
+ boolean[] primitiveValues = new boolean[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Boolean) values.get(count)).booleanValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("char")) {
+ char[] primitiveValues = new char[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Character) values.get(count)).charValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("byte")) {
+ byte[] primitiveValues = new byte[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Byte) values.get(count)).byteValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("short")) {
+ short[] primitiveValues = new short[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Short) values.get(count)).shortValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("long")) {
+ long[] primitiveValues = new long[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Long) values.get(count)).longValue();
+ }
+ return primitiveValues;
+ } else if (fieldType.getName().equals("double")) {
+ double[] primitiveValues = new double[values.size()];
+ for (int count = 0; count < values.size(); ++count) {
+ primitiveValues[count] = ((Double) values.get(count)).doubleValue();
+ }
+ return primitiveValues;
+ }
+ }
+ return values;
+ }
+
+ public abstract String getText(T source) throws XML2JavaMapperException;
+
+ public abstract List<T> getChildElements(T parent) throws XML2JavaMapperException;
+
+ public abstract String getElementName(T element) throws XML2JavaMapperException;
+
+ public abstract boolean isTextElement(T element) throws XML2JavaMapperException;
+
+ public abstract T getRootElement(T element) throws XML2JavaMapperException;
+
+ @Override
+ public Class getTargetType() {
+ return Object.class;
+ }
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.java new file mode 100644 index 0000000000..b7dee262c0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.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.tuscany.sca.databinding.javabeans;
+
+import javax.xml.namespace.QName;
+
+/**
+ * This exception is used to encapsulate and rethrow exceptions that arise out
+ * of converting XML Data to Java Objects.
+ */
+public class XML2JavaMapperException extends RuntimeException {
+ private static final long serialVersionUID = 6596530102591630642L;
+
+ private QName xmlElementName;
+ private String javaFieldName;
+ private Class javaType;
+
+ public XML2JavaMapperException(String message) {
+ super(message);
+ }
+
+ public XML2JavaMapperException(Throwable cause) {
+ super(cause);
+ }
+
+ public QName getXmlElementName() {
+ return xmlElementName;
+ }
+
+ public void setXmlElementName(QName xmlElementName) {
+ this.xmlElementName = xmlElementName;
+ }
+
+ public String getJavaFieldName() {
+ return javaFieldName;
+ }
+
+ public void setJavaFieldName(String javaFieldName) {
+ this.javaFieldName = javaFieldName;
+ }
+
+ public Class getJavaType() {
+ return javaType;
+ }
+
+ public void setJavaType(Class javaType) {
+ this.javaType = javaType;
+ }
+
+ @Override
+ public String getMessage() {
+ return super.getMessage() + " <" + getJavaFieldName() + "> " + " in <" + getJavaType() + ">";
+ }
+
+
+
+}
diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanUtil.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanUtil.java new file mode 100644 index 0000000000..3c39c8d4cc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanUtil.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.tuscany.sca.databinding.xml; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; + +public final class BeanUtil { + private static final Object[] NULL = null; + private static int nsCount = 1; + + private static final SimpleTypeMapperImpl MAPPER = new SimpleTypeMapperImpl(); + + private BeanUtil() { + } + + private static boolean isSimpleType(Class javaType) { + return SimpleTypeMapperImpl.getXMLType(javaType) != null; + } + + private static String getStringValue(Object o) { + if (o == null) { + return null; + } + TypeInfo info = SimpleTypeMapperImpl.getXMLType(o.getClass()); + if (info != null) { + return MAPPER.toXMLLiteral(info.getQName(), o, null); + } else { + return String.valueOf(o); + } + } + + /** + * To Serilize Bean object this method is used, this will create an object + * array using given bean object + * + * @param beanObject + * @param beanName + */ + public static XMLStreamReader getXMLStreamReader(Object beanObject, QName beanName) { + try { + ClassLoader cl = beanObject.getClass().getClassLoader(); + if (cl == null) { + //FIXME Wouldn't it be better to use the current thread context + // classloader? + cl = ClassLoader.getSystemClassLoader(); + } + String beanNS = beanName.getNamespaceURI(); + String beanPrefix = beanName.getPrefix(); + BeanInfo beanInfo = Introspector.getBeanInfo(beanObject.getClass()); + PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors(); + Map<String, PropertyDescriptor> propertMap = new HashMap<String, PropertyDescriptor>(); + for (int i = 0; i < propDescs.length; i++) { + PropertyDescriptor propDesc = propDescs[i]; + propertMap.put(propDesc.getName(), propDesc); + } + List<String> properties = new ArrayList<String>(propertMap.keySet()); + Collections.sort(properties); + List<NamedProperty> props = new ArrayList<NamedProperty>(); + for (int i = 0; i < properties.size(); i++) { + String property = properties.get(i); + PropertyDescriptor propDesc = propertMap.get(property); + if (propDesc == null) { + // JAM does bad thing so I need to add this + continue; + } + Class ptype = propDesc.getPropertyType(); + if ("class".equals(property)) { + continue; + } + if (isSimpleType(ptype)) { + Object value = propDesc.getReadMethod().invoke(beanObject, NULL); + NamedProperty prop = + new NamedProperty(new QName(beanNS, property, beanPrefix), getStringValue(value)); + props.add(prop); + } else if (ptype.isArray()) { + if (isSimpleType(ptype.getComponentType())) { + Object value = propDesc.getReadMethod().invoke(beanObject, NULL); + if (value != null) { + int i1 = Array.getLength(value); + for (int j = 0; j < i1; j++) { + Object o = Array.get(value, j); + NamedProperty prop = + new NamedProperty(new QName(beanNS, property, beanPrefix), getStringValue(o)); + props.add(prop); + } + } else { + NamedProperty prop = new NamedProperty(new QName(beanNS, property, beanPrefix), value); + props.add(prop); + } + + } else { + Object value[] = (Object[])propDesc.getReadMethod().invoke(beanObject, NULL); + if (value != null) { + for (int j = 0; j < value.length; j++) { + Object o = value[j]; + NamedProperty prop = + new NamedProperty(new QName(beanNS, property, beanPrefix), getStringValue(o)); + props.add(prop); + } + } else { + NamedProperty prop = new NamedProperty(new QName(beanNS, property, beanPrefix), value); + props.add(prop); + } + } + } else if (Collection.class.isAssignableFrom(ptype)) { + Object value = propDesc.getReadMethod().invoke(beanObject, NULL); + Collection objList = (Collection)value; + if (objList != null && objList.size() > 0) { + // this was given error , when the array.size = 0 + // and if the array contain simple type , then the + // ADBPullParser asked + // PullParser from That simpel type + for (Iterator j = objList.iterator(); j.hasNext();) { + Object o = j.next(); + if (isSimpleType(o.getClass())) { + NamedProperty prop = + new NamedProperty(new QName(beanNS, property, beanPrefix), getStringValue(o)); + props.add(prop); + } else { + NamedProperty prop = new NamedProperty(new QName(beanNS, property, beanPrefix), o); + props.add(prop); + } + } + + } else { + NamedProperty prop = new NamedProperty(new QName(beanNS, property, beanPrefix), value); + props.add(prop); + } + } else { + Object value = propDesc.getReadMethod().invoke(beanObject, NULL); + NamedProperty prop = new NamedProperty(new QName(beanNS, property, beanPrefix), value); + props.add(prop); + } + } + NamedProperty[] elements = new NamedProperty[props.size()]; + props.toArray(elements); + return new XMLFragmentStreamReaderImpl(beanName, elements, null); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + /** + * to get the pull parser for a given bean object , generate the wrpper + * element using class name + * + * @param beanObject + */ + public static XMLStreamReader getXMLStreamReader(Object beanObject) { + String className = beanObject.getClass().getName(); + if (className.indexOf(".") > 0) { + className = className.substring(className.lastIndexOf('.') + 1, className.length()); + } + return getXMLStreamReader(beanObject, new QName(className)); + } + + /** + * increments the namespace counter and returns a new prefix + * + * @return unique prefix + */ + public static String getUniquePrefix() { + return "s" + nsCount++; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.java new file mode 100644 index 0000000000..9e3d352ac8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.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.tuscany.sca.databinding.xml; + + +import java.lang.annotation.Annotation; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.w3c.dom.Node; + +/** + * DOM DataBinding + * + * @version $Rev$ $Date$ + */ +public class DOMDataBinding extends BaseDataBinding { + public static final String NAME = Node.class.getName(); + public static final String[] ALIASES = new String[] {"dom"}; + + public static final String ROOT_NAMESPACE = "http://tuscany.apache.org/xmlns/sca/databinding/dom/1.0"; + public static final QName ROOT_ELEMENT = new QName(ROOT_NAMESPACE, "root"); + + public DOMDataBinding() { + super(NAME, ALIASES, Node.class); + } + + @Override + public WrapperHandler getWrapperHandler() { + return new DOMWrapperHandler(); + } + + @Override + public Object copy(Object source) { + if (Node.class.isAssignableFrom(source.getClass())) { + Node nodeSource = (Node) source; + return nodeSource.cloneNode(true); + } + return super.copy(source); + } + + @Override + public boolean introspect(DataType type, Annotation[] annotations) { + if(Node.class.isAssignableFrom(type.getPhysical())) { + type.setLogical(new XMLType(ROOT_ELEMENT, null)); + return true; + } + return false; + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.java new file mode 100644 index 0000000000..849912dc80 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.xml; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class DOMWrapperHandler implements WrapperHandler<Node> { + + public DOMWrapperHandler() { + super(); + } + + public Node create(ElementInfo element, TransformationContext context) { + try { + Document document = DOMHelper.newDocument(); + QName name = element.getQName(); + return DOMHelper.createElement(document, name); + } catch (ParserConfigurationException e) { + throw new TransformationException(e); + } + } + + public void setChild(Node wrapper, int i, ElementInfo childElement, Object value) { + Node node = (Node)value; + if (node.getNodeType() == Node.DOCUMENT_NODE) { + node = ((Document)node).getDocumentElement(); + } + wrapper.appendChild(wrapper.getOwnerDocument().importNode(node, true)); + } + + public List getChildren(Node wrapper, List<ElementInfo> childElements, TransformationContext context) { + assert wrapper != null; + if (wrapper.getNodeType() == Node.DOCUMENT_NODE) { + wrapper = ((Document)wrapper).getDocumentElement(); + } + List<Node> elements = new ArrayList<Node>(); + NodeList nodes = wrapper.getChildNodes(); + for (int j = 0; j < nodes.getLength(); j++) { + Node node = nodes.item(j); + if (node.getNodeType() == Node.ELEMENT_NODE) { + elements.add(node); + } + } + return elements; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#getWrapperType(org.apache.tuscany.sca.interfacedef.util.ElementInfo, List, org.apache.tuscany.sca.databinding.TransformationContext) + */ + public DataType getWrapperType(ElementInfo element, List<ElementInfo> childElements, TransformationContext context) { + DataType<XMLType> wrapperType = + new DataTypeImpl<XMLType>(DOMDataBinding.NAME, Node.class, new XMLType(element)); + return wrapperType; + } + + public boolean isInstance(Object wrapperObj, + ElementInfo element, + List<ElementInfo> childElements, + TransformationContext context) { + Node wrapper = (Node)wrapperObj; + if (wrapper.getNodeType() == Node.DOCUMENT_NODE) { + wrapper = ((Document)wrapper).getDocumentElement(); + } + QName elementName = new QName(wrapper.getNamespaceURI(), wrapper.getLocalName()); + if (!element.getQName().equals(elementName)) { + return false; + } + Set<QName> names = new HashSet<QName>(); + for (ElementInfo e : childElements) { + names.add(e.getQName()); + } + NodeList nodes = wrapper.getChildNodes(); + for (int j = 0; j < nodes.getLength(); j++) { + Node node = nodes.item(j); + if (node.getNodeType() == Node.ELEMENT_NODE) { + elementName = new QName(wrapper.getNamespaceURI(), wrapper.getLocalName()); + if (!names.contains(elementName)) { + return false; + } + } + } + return true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMXMLStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMXMLStreamReader.java new file mode 100644 index 0000000000..e377dd1d8b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMXMLStreamReader.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX; +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.w3c.dom.Attr; +import org.w3c.dom.CharacterData; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class DOMXMLStreamReader extends XMLFragmentStreamReaderImpl { + private Element rootElement; + + public DOMXMLStreamReader(Node node) { + super(null); + switch (node.getNodeType()) { + case Node.DOCUMENT_NODE: + this.rootElement = ((Document)node).getDocumentElement(); + break; + case Node.ELEMENT_NODE: + this.rootElement = (Element)node; + break; + default: + throw new IllegalArgumentException("Illegal Node"); + } + String ns = rootElement.getNamespaceURI(); + String prefix = rootElement.getPrefix(); + String name = rootElement.getLocalName(); + elementQName = new QName(ns == null ? "" : ns, name, prefix == null ? "" : prefix); + } + + @Override + protected final NamedProperty[] getAttributes() { + if (attributes == null) { + List<NamedProperty> attributeList = new ArrayList<NamedProperty>(); + NamedNodeMap nodeMap = rootElement.getAttributes(); + for (int i = 0; i < nodeMap.getLength(); i++) { + Attr attr = (Attr)nodeMap.item(i); + String ns = attr.getNamespaceURI(); + String prefix = attr.getPrefix(); + if (!XMLNS_ATTRIBUTE_NS_URI.equals(ns)) { + QName attrName = new QName(ns == null ? "" : ns, attr.getLocalName(), prefix != null ? prefix : ""); + NamedProperty pair = new NamedProperty(attrName, attr.getValue()); + attributeList.add(pair); + } + } + attributes = new NamedProperty[attributeList.size()]; + attributeList.toArray(attributes); + } + return attributes; + } + + @Override + protected QName[] getNamespaces() { + List<QName> nsList = new ArrayList<QName>(); + NamedNodeMap nodeMap = rootElement.getAttributes(); + for (int i = 0; i < nodeMap.getLength(); i++) { + Attr attr = (Attr)nodeMap.item(i); + String ns = attr.getNamespaceURI(); + if (XMLNS_ATTRIBUTE_NS_URI.equals(ns)) { + String prefix = attr.getPrefix(); + if (prefix == null) { + // xmlns="http://ns" + nsList.add(new QName(attr.getValue(), "", DEFAULT_NS_PREFIX)); + } else { + // xmlns:ns="http://ns" + nsList.add(new QName(attr.getValue(), "", attr.getLocalName())); + } + } + } + QName[] nss = new QName[nsList.size()]; + nsList.toArray(nss); + return nss; + } + + @Override + protected NamedProperty[] getElements() { + if (elements == null) { + List<NamedProperty> elementList = new ArrayList<NamedProperty>(); + NodeList nodeList = rootElement.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + switch (node.getNodeType()) { + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + NamedProperty pair = new NamedProperty(ELEMENT_TEXT, ((CharacterData)node).getData()); + elementList.add(pair); + break; + + case Node.ELEMENT_NODE: + Element element = (Element)node; + QName elementName = new QName(element.getNamespaceURI(), element.getLocalName()); + pair = new NamedProperty(elementName, new DOMXMLStreamReader(element)); + elementList.add(pair); + break; + } + } + elements = new NamedProperty[elementList.size()]; + elementList.toArray(elements); + } + return elements; + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DelegatingNamespaceContext.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DelegatingNamespaceContext.java new file mode 100644 index 0000000000..40d5c07499 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DelegatingNamespaceContext.java @@ -0,0 +1,310 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.util.ArrayList; +import java.util.EmptyStackException; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.NamespaceContext; + +public class DelegatingNamespaceContext implements NamespaceContext { + private static int count; + + private class WrappingIterator implements Iterator { + + private Iterator containedIterator; + + public WrappingIterator(Iterator containedIterator) { + this.containedIterator = containedIterator; + } + + public Iterator getContainedIterator() { + return containedIterator; + } + + public boolean hasNext() { + return containedIterator.hasNext(); + } + + public Object next() { + return containedIterator.next(); + } + + /** + * As per the contract on the API of Namespace context the returned iterator should be immutable + */ + public void remove() { + throw new UnsupportedOperationException(); + } + + public void setContainedIterator(Iterator containedIterator) { + this.containedIterator = containedIterator; + } + } + + private NamespaceContext parentNsContext; + + private FastStack<String> prefixStack = new FastStack<String>(); + + // Keep two arraylists for the prefixes and namespaces. They should be in + // sync + // since the index of the entry will be used to relate them + // use the minimum initial capacity to let things handle memory better + + private FastStack<String> uriStack = new FastStack<String>(); + + /** + * Generates a unique namespace prefix that is not in the scope of the NamespaceContext + * + * @return string + */ + public String generateUniquePrefix() { + String prefix = "p" + count++; + // null should be returned if the prefix is not bound! + while (getNamespaceURI(prefix) != null) { + prefix = "p" + count++; + } + + return prefix; + } + + public String getNamespaceURI(String prefix) { + // do the corrections as per the javadoc + int index = prefixStack.search(prefix); + if (index != -1) { + return uriStack.get(index); + } + if (parentNsContext != null) { + return parentNsContext.getPrefix(prefix); + } + return null; + } + + public NamespaceContext getParentNsContext() { + return parentNsContext; + } + + public String getPrefix(String uri) { + // do the corrections as per the javadoc + int index = uriStack.search(uri); + if (index != -1) { + return prefixStack.get(index); + } + + if (parentNsContext != null) { + return parentNsContext.getPrefix(uri); + } + return null; + } + + public Iterator getPrefixes(String uri) { + // create an arraylist that contains the relevant prefixes + String[] uris = uriStack.toArray(new String[uriStack.size()]); + List<String> tempList = new ArrayList<String>(); + for (int i = uris.length - 1; i >= 0; i--) { + if (uris[i].equals(uri)) { + tempList.add(prefixStack.get(i)); + // we assume that array conversion preserves the order + } + } + // by now all the relevant prefixes are collected + // make a new iterator and provide a wrapper iterator to + // obey the contract on the API + return new WrappingIterator(tempList.iterator()); + } + + /** + * Pop a namespace + */ + public void popNamespace() { + prefixStack.pop(); + uriStack.pop(); + } + + /** + * Register a namespace in this context + * + * @param prefix + * @param uri + */ + public void pushNamespace(String prefix, String uri) { + prefixStack.push(prefix); + uriStack.push(uri); + + } + + public void setParentNsContext(NamespaceContext parentNsContext) { + this.parentNsContext = parentNsContext; + } + + /** + * An implementation of the {@link java.util.Stack} API that is based on an <code>ArrayList</code> instead of a + * <code>Vector</code>, so it is not synchronized to protect against multi-threaded access. The implementation is + * therefore operates faster in environments where you do not need to worry about multiple thread contention. + * <p> + * The removal order of an <code>ArrayStack</code> is based on insertion order: The most recently added element is + * removed first. The iteration order is <i>not</i> the same as the removal order. The iterator returns elements + * from the bottom up, whereas the {@link #remove()} method removes them from the top down. + * <p> + * Unlike <code>Stack</code>, <code>ArrayStack</code> accepts null entries. + */ + public static class FastStack<T> extends ArrayList<T> { + + /** Ensure serialization compatibility */ + private static final long serialVersionUID = 2130079159931574599L; + + /** + * Constructs a new empty <code>ArrayStack</code>. The initial size is controlled by <code>ArrayList</code> + * and is currently 10. + */ + public FastStack() { + super(); + } + + /** + * Constructs a new empty <code>ArrayStack</code> with an initial size. + * + * @param initialSize the initial size to use + * @throws IllegalArgumentException if the specified initial size is negative + */ + public FastStack(int initialSize) { + super(initialSize); + } + + /** + * Return <code>true</code> if this stack is currently empty. + * <p> + * This method exists for compatibility with <code>java.util.Stack</code>. New users of this class should use + * <code>isEmpty</code> instead. + * + * @return true if the stack is currently empty + */ + public boolean empty() { + return isEmpty(); + } + + /** + * Returns the top item off of this stack without removing it. + * + * @return the top item on the stack + * @throws EmptyStackException if the stack is empty + */ + public T peek() throws EmptyStackException { + int n = size(); + if (n <= 0) { + throw new EmptyStackException(); + } else { + return get(n - 1); + } + } + + /** + * Returns the n'th item down (zero-relative) from the top of this stack without removing it. + * + * @param n the number of items down to go + * @return the n'th item on the stack, zero relative + * @throws EmptyStackException if there are not enough items on the stack to satisfy this request + */ + public T peek(int n) throws EmptyStackException { + int m = (size() - n) - 1; + if (m < 0) { + throw new EmptyStackException(); + } else { + return get(m); + } + } + + /** + * Pops the top item off of this stack and return it. + * + * @return the top item on the stack + * @throws EmptyStackException if the stack is empty + */ + public T pop() throws EmptyStackException { + int n = size(); + if (n <= 0) { + throw new EmptyStackException(); + } else { + return remove(n - 1); + } + } + + /** + * Pushes a new item onto the top of this stack. The pushed item is also returned. This is equivalent to calling + * <code>add</code>. + * + * @param item the item to be added + * @return the item just pushed + */ + public Object push(T item) { + add(item); + return item; + } + + /** + * Returns the top-most index for the object in the stack + * + * @param object the object to be searched for + * @return top-most index, or -1 if not found + */ + public int search(T object) { + int i = size() - 1; // Current index + while (i >= 0) { + T current = get(i); + if ((object == null && current == null) || (object != null && object.equals(current))) { + return i; + } + i--; + } + return -1; + } + + /** + * Returns the element on the top of the stack. + * + * @return the element on the top of the stack + * @throws EmptyStackException if the stack is empty + */ + public T get() { + int size = size(); + if (size == 0) { + throw new EmptyStackException(); + } + return get(size - 1); + } + + /** + * Removes the element on the top of the stack. + * + * @return the removed element + * @throws EmptyStackException if the stack is empty + */ + public T remove() { + int size = size(); + if (size == 0) { + throw new EmptyStackException(); + } + return remove(size - 1); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.java new file mode 100644 index 0000000000..2a6094a76a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * Push DOM InputSource to Node + */ +public class InputSource2Node extends BaseTransformer<InputSource, Node> implements + PullTransformer<InputSource, Node> { + private static final Source2ResultTransformer TRANSFORMER = new Source2ResultTransformer(); + + public Node transform(InputSource source, TransformationContext context) { + try { + Source streamSource = new StreamSource(source.getCharacterStream()); + DOMResult result = new DOMResult(); + TRANSFORMER.transform(streamSource, result, context); + return result.getNode(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputSource.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.java new file mode 100644 index 0000000000..d842048d81 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.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.tuscany.sca.databinding.xml; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * Push InputSource to SAX + */ +public class InputSource2SAX extends BaseTransformer<InputSource, ContentHandler> implements + PushTransformer<InputSource, ContentHandler> { + + public void transform(InputSource source, ContentHandler target, TransformationContext context) { + try { + XMLReader reader = XMLReaderFactory.createXMLReader(); + reader.setFeature("http://xml.org/sax/features/namespaces", true); + reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); + reader.setContentHandler(target); + reader.parse(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputSource.class; + } + + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.java new file mode 100644 index 0000000000..2ec864fbbd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.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.tuscany.sca.databinding.xml; + +import java.io.InputStream; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.sax.SAXSource; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * Push DOM InputSource to Node + */ +public class InputStream2Node extends BaseTransformer<InputStream, Node> implements + PullTransformer<InputStream, Node> { + private static final Source2ResultTransformer TRANSFORMER = new Source2ResultTransformer(); + + public Node transform(InputStream source, TransformationContext context) { + try { + Source streamSource = new SAXSource(new InputSource(source)); + DOMResult result = new DOMResult(); + TRANSFORMER.transform(streamSource, result, context); + return result.getNode(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputStream.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.java new file mode 100644 index 0000000000..06b2521d47 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.io.InputStream; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * Push InputStream to SAX + */ +public class InputStream2SAX extends BaseTransformer<InputStream, ContentHandler> implements + PushTransformer<InputStream, ContentHandler> { + public void transform(InputStream source, ContentHandler target, TransformationContext context) { + try { + XMLReader reader = XMLReaderFactory.createXMLReader(); + reader.setContentHandler(target); + reader.parse(new InputSource(source)); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputStream.class; + } + + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NameValueArrayStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NameValueArrayStreamReader.java new file mode 100644 index 0000000000..157a95025d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NameValueArrayStreamReader.java @@ -0,0 +1,403 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; + +public class NameValueArrayStreamReader implements XMLFragmentStreamReader { + + private static final int START_ELEMENT_STATE = 0; + private static final int TEXT_STATE = 1; + private static final int END_ELEMENT_STATE = 2; + private static final int FINAL_END_ELEMENT_STATE = 3; + private static final int START_ELEMENT_STATE_WITH_NULL = 4; + + private DelegatingNamespaceContext namespaceContext = new DelegatingNamespaceContext(); + // the index of the array + private int arrayIndex; + + private QName name; + private String[] values; + + // start element is the default state + private int state = START_ELEMENT_STATE; + + public NameValueArrayStreamReader(QName name, String[] values) { + this.name = name; + this.values = values; + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + this.namespaceContext.setParentNsContext(nsContext); + } + + public void init() { + // todo what if the Qname namespace has not been declared + } + + public Object getProperty(String string) throws IllegalArgumentException { + return null; + } + + /** + * @throws XMLStreamException + */ + public int next() throws XMLStreamException { + switch (state) { + case START_ELEMENT_STATE: + if (values.length > 0) { + state = TEXT_STATE; + return CHARACTERS; + } else { + state = FINAL_END_ELEMENT_STATE; + return END_ELEMENT; + } + + case START_ELEMENT_STATE_WITH_NULL: + if (arrayIndex == (values.length - 1)) { + state = FINAL_END_ELEMENT_STATE; + } else { + state = END_ELEMENT_STATE; + } + return END_ELEMENT; + case FINAL_END_ELEMENT_STATE: + // oops, not supposed to happen! + throw new XMLStreamException("end already reached!"); + case END_ELEMENT_STATE: + // we've to have more values since this is not the + // last value + // increment the counter + arrayIndex++; + if (values[arrayIndex] == null) { + state = START_ELEMENT_STATE_WITH_NULL; + } else { + state = START_ELEMENT_STATE; + } + return START_ELEMENT; + case TEXT_STATE: + if (arrayIndex == (values.length - 1)) { + state = FINAL_END_ELEMENT_STATE; + return END_ELEMENT; + } else { + state = END_ELEMENT_STATE; + return END_ELEMENT; + } + + default: + throw new XMLStreamException("unknown event type!"); + } + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // nothing done here + } + + public String getElementText() throws XMLStreamException { + return null; // not implemented + } + + public int nextTag() throws XMLStreamException { + return 0; // not implemented + } + + public String getAttributeValue(String string, String string1) { + if (state == TEXT_STATE) { + // todo something + return null; + } else { + return null; + } + + } + + public int getAttributeCount() { + if (state == START_ELEMENT_STATE_WITH_NULL) { + return 1; + } + if (state == START_ELEMENT_STATE) { + return 0; + } else { + throw new IllegalStateException(); + } + + } + + public QName getAttributeName(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME; + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeNamespace(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME.getNamespaceURI(); + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeLocalName(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME.getLocalPart(); + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributePrefix(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME.getPrefix(); + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeType(int i) { + return null; // not implemented + } + + public String getAttributeValue(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_VALUE_TRUE; + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public boolean isAttributeSpecified(int i) { + return false; // not supported + } + + public int getNamespaceCount() { + if (state == START_ELEMENT_STATE_WITH_NULL && isXsiNamespacePresent()) { + return 1; + } else { + return 0; + } + + } + + public String getNamespacePrefix(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && isXsiNamespacePresent() && i == 0) { + return NIL_QNAME.getPrefix(); + } else { + return null; + } + } + + public String getNamespaceURI(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && isXsiNamespacePresent() && i == 0) { + return NIL_QNAME.getNamespaceURI(); + } else { + return null; + } + } + + public NamespaceContext getNamespaceContext() { + return this.namespaceContext; + } + + public boolean isDone() { + return state == FINAL_END_ELEMENT_STATE; + } + + public int getEventType() { + switch (state) { + case START_ELEMENT_STATE: + return START_ELEMENT; + case END_ELEMENT_STATE: + return END_ELEMENT; + case TEXT_STATE: + return CHARACTERS; + case FINAL_END_ELEMENT_STATE: + return END_ELEMENT; + default: + throw new UnsupportedOperationException(); + // we've no idea what this is!!!!! + } + + } + + public String getText() { + if (state == TEXT_STATE) { + return values[arrayIndex]; + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (state == TEXT_STATE) { + return values[arrayIndex].toCharArray(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + // not implemented + throw new UnsupportedOperationException(); + } + + public int getTextStart() { + if (state == TEXT_STATE) { + return 0; + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (state == TEXT_STATE) { + return values[arrayIndex].length(); + } else { + throw new IllegalStateException(); + } + + } + + public String getEncoding() { + return null; + } + + public boolean hasText() { + return state == TEXT_STATE; + } + + public Location getLocation() { + return null; // not supported + } + + public QName getName() { + if (state != TEXT_STATE) { + return name; + } else { + return null; + } + } + + public String getLocalName() { + if (state != TEXT_STATE) { + return name.getLocalPart(); + } else { + return null; + } + } + + public boolean hasName() { + return state != TEXT_STATE; + + } + + public String getNamespaceURI() { + if (state != TEXT_STATE) { + return name.getNamespaceURI(); + } else { + return null; + } + + } + + public String getPrefix() { + if (state != TEXT_STATE) { + return name.getPrefix(); + } else { + return null; + } + } + + public String getVersion() { + return null; // todo 1.0 ? + } + + public boolean isStandalone() { + return false; + } + + public boolean standaloneSet() { + return false; + } + + public String getCharacterEncodingScheme() { + return null; + } + + public String getPITarget() { + return null; + } + + public String getPIData() { + return null; + } + + public boolean hasNext() throws XMLStreamException { + return state != FINAL_END_ELEMENT_STATE; + } + + public void close() throws XMLStreamException { + // Do nothing - we've nothing to free here + } + + public String getNamespaceURI(String prefix) { + return namespaceContext.getNamespaceURI(prefix); + } + + public boolean isStartElement() { + return state == START_ELEMENT_STATE; + } + + public boolean isEndElement() { + return state == END_ELEMENT_STATE; + } + + public boolean isCharacters() { + return state == TEXT_STATE; + } + + public boolean isWhiteSpace() { + return false; // no whitespaces here + } + + /** + * Test whether the xsi namespace is present + */ + private boolean isXsiNamespacePresent() { + return namespaceContext.getNamespaceURI(NIL_QNAME.getPrefix()) != null; + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NameValuePairStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NameValuePairStreamReader.java new file mode 100644 index 0000000000..71af7519e7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NameValuePairStreamReader.java @@ -0,0 +1,347 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; + + +public class NameValuePairStreamReader implements XMLFragmentStreamReader { + + private static final int START_ELEMENT_STATE = 0; + private static final int TEXT_STATE = 1; + private static final int END_ELEMENT_STATE = 2; + + private DelegatingNamespaceContext namespaceContext = new DelegatingNamespaceContext(); + + private QName name; + private String value; + + private int state = START_ELEMENT_STATE; + // initiate at the start element state + + // keeps track whether the namespace is declared + // false by default + private boolean nsDeclared; + + public NameValuePairStreamReader(QName name, String value) { + this.name = name; + this.value = value; + } + + public Object getProperty(String key) throws IllegalArgumentException { + return null; + } + + public int next() throws XMLStreamException { + // no need to handle null here. it should have been handled + // already + switch (state) { + case START_ELEMENT_STATE: + state = TEXT_STATE; + return CHARACTERS; + case END_ELEMENT_STATE: + // oops, not supposed to happen! + throw new XMLStreamException("end already reached!"); + case TEXT_STATE: + state = END_ELEMENT_STATE; + return END_ELEMENT; + default: + throw new XMLStreamException("unknown event type!"); + } + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // not implemented + } + + public String getElementText() throws XMLStreamException { + if (state == START_ELEMENT) { + // move to the end state and return the value + state = END_ELEMENT_STATE; + return value; + } else { + throw new XMLStreamException(); + } + + } + + public int nextTag() throws XMLStreamException { + return 0; // todo + } + + public boolean hasNext() throws XMLStreamException { + return state != END_ELEMENT_STATE; + } + + public void close() throws XMLStreamException { + // Do nothing - we've nothing to free here + } + + public String getNamespaceURI(String prefix) { + return namespaceContext.getNamespaceURI(prefix); + } + + public boolean isStartElement() { + return state == START_ELEMENT_STATE; + } + + public boolean isEndElement() { + return state == END_ELEMENT_STATE; + } + + public boolean isCharacters() { + return state == TEXT_STATE; + } + + public boolean isWhiteSpace() { + return false; // no whitespaces here + } + + public String getAttributeValue(String string, String string1) { + return null; + } + + public int getAttributeCount() { + return 0; + } + + public QName getAttributeName(int i) { + return null; + } + + public String getAttributeNamespace(int i) { + return null; + } + + public String getAttributeLocalName(int i) { + return null; + } + + public String getAttributePrefix(int i) { + return null; + } + + public String getAttributeType(int i) { + return null; + } + + public String getAttributeValue(int i) { + return null; + } + + public boolean isAttributeSpecified(int i) { + return false; // no attribs here + } + + public int getNamespaceCount() { + return nsDeclared ? 1 : 0; + } + + public String getNamespacePrefix(int i) { + return (nsDeclared && i == 0) ? name.getPrefix() : null; + } + + public String getNamespaceURI(int i) { + return (nsDeclared && i == 0) ? name.getNamespaceURI() : null; + } + + public NamespaceContext getNamespaceContext() { + return this.namespaceContext; + } + + public int getEventType() { + switch (state) { + case START_ELEMENT_STATE: + return START_ELEMENT; + case END_ELEMENT_STATE: + return END_ELEMENT; + case TEXT_STATE: + return CHARACTERS; + default: + throw new UnsupportedOperationException(); + // we've no idea what this is!!!!! + } + + } + + public String getText() { + if (state == TEXT_STATE) { + return value; + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (state == TEXT_STATE) { + return value.toCharArray(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + // not implemented + throw new UnsupportedOperationException(); + } + + public int getTextStart() { + if (state == TEXT_STATE) { + return 0; + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (state == TEXT_STATE) { + return value.length(); + } else { + throw new IllegalStateException(); + } + + } + + public String getEncoding() { + return null; + } + + public boolean hasText() { + return state == TEXT_STATE; + } + + public Location getLocation() { + return new Location() { + public int getLineNumber() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getCharacterOffset() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + if (state != TEXT_STATE) { + return name; + } else { + return null; + } + } + + public String getLocalName() { + if (state != TEXT_STATE) { + return name.getLocalPart(); + } else { + return null; + } + } + + public boolean hasName() { + return state != TEXT_STATE; + + } + + public String getNamespaceURI() { + if (state != TEXT_STATE) { + return name.getNamespaceURI(); + } else { + return null; + } + + } + + public String getPrefix() { + if (state != TEXT_STATE) { + return name.getPrefix(); + } else { + return null; + } + } + + public String getVersion() { + return null; // todo 1.0 ? + } + + public boolean isStandalone() { + return false; + } + + public boolean standaloneSet() { + return false; + } + + public String getCharacterEncodingScheme() { + return null; + } + + public String getPITarget() { + return null; + } + + public String getPIData() { + return null; + } + + public boolean isDone() { + return state == END_ELEMENT_STATE; + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + this.namespaceContext.setParentNsContext(nsContext); + } + + public void init() { + // just add the current elements namespace and prefix to the this + // elements nscontext + addToNsMap(name.getPrefix(), name.getNamespaceURI()); + + } + + /** + * @param prefix + * @param uri + */ + private void addToNsMap(String prefix, String uri) { + // todo - need to fix this up to cater for cases where + // namespaces are having no prefixes + if (!uri.equals(namespaceContext.getNamespaceURI(prefix))) { + // this namespace is not there. Need to declare it + namespaceContext.pushNamespace(prefix, uri); + nsDeclared = true; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NamedProperty.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NamedProperty.java new file mode 100644 index 0000000000..04d7d65a0d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NamedProperty.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.xml; + +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * A named property + * + * @version $Rev$ $Date$ + */ +public class NamedProperty implements Map.Entry<QName, Object> { + private QName key; + + private Object value; + + public NamedProperty(QName key, Object value) { + this.key = key; + this.value = value; + } + + public NamedProperty(String key, Object value) { + this.key = new QName(key); + this.value = value; + } + + public QName getKey() { + return key; + } + + public Object getValue() { + return value; + } + + public Object setValue(Object value) { + Object v = this.value; + this.value = value; + return v; + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NilElementStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NilElementStreamReader.java new file mode 100644 index 0000000000..abc4bf3785 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/NilElementStreamReader.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.tuscany.sca.databinding.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; + +public class NilElementStreamReader implements XMLFragmentStreamReader { + + private static final int END_ELEMENT_STATE = 2; + + private static final int START_ELEMENT_STATE = 1; + private int currentState = START_ELEMENT; + + private QName elementQName; + + public NilElementStreamReader(QName elementQName) { + this.elementQName = elementQName; + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + // NOOP + } + + public void close() throws XMLStreamException { + // do nothing + } + + public int getAttributeCount() { + return 1; + } + + public String getAttributeLocalName(int i) { + return (i == 0) ? NIL_QNAME.getLocalPart() : null; + } + + public QName getAttributeName(int i) { + return (i == 0) ? NIL_QNAME : null; + } + + public String getAttributeNamespace(int i) { + return (i == 0) ? NIL_QNAME.getNamespaceURI() : null; + } + + public String getAttributePrefix(int i) { + return (i == 0) ? NIL_QNAME.getPrefix() : null; + } + + public String getAttributeType(int i) { + throw new UnsupportedOperationException(); + } + + public String getAttributeValue(int i) { + return (i == 0) ? NIL_VALUE_TRUE : null; + } + + public String getAttributeValue(String string, String string1) { + if (string == null && NIL_QNAME.getLocalPart().equals(string1)) { + return NIL_VALUE_TRUE; + } + return null; + } + + public String getCharacterEncodingScheme() { + throw new UnsupportedOperationException(); + } + + public String getElementText() throws XMLStreamException { + return null; + } + + public String getEncoding() { + return null; + } + + public int getEventType() { + int returnEvent = START_DOCUMENT; + switch (currentState) { + case START_ELEMENT_STATE: + returnEvent = START_ELEMENT; + break; + case END_ELEMENT_STATE: + returnEvent = END_ELEMENT; + break; + } + return returnEvent; + } + + public String getLocalName() { + return elementQName.getLocalPart(); + } + + public Location getLocation() { + return new Location() { + public int getCharacterOffset() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getLineNumber() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + return elementQName; + } + + public NamespaceContext getNamespaceContext() { + throw new UnsupportedOperationException(); + } + + public int getNamespaceCount() { + return 0; + } + + public String getNamespacePrefix(int i) { + return null; + } + + public String getNamespaceURI() { + return elementQName.getNamespaceURI(); + } + + public String getNamespaceURI(int i) { + return null; + } + + public String getNamespaceURI(String string) { + if (elementQName.getPrefix() != null && elementQName.getPrefix().equals(string)) { + return elementQName.getNamespaceURI(); + } else { + return null; + } + } + + public String getPIData() { + throw new UnsupportedOperationException(); + } + + public String getPITarget() { + throw new UnsupportedOperationException(); + } + + public String getPrefix() { + return elementQName.getPrefix(); + } + + public Object getProperty(String key) throws IllegalArgumentException { + // since optimization is a global property + // we've to implement it everywhere + return null; + } + + public String getText() { + return null; + } + + public char[] getTextCharacters() { + return new char[0]; + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + return 0; + } + + public int getTextLength() { + return 0; + } + + public int getTextStart() { + return 0; + } + + public String getVersion() { + throw new UnsupportedOperationException(); + } + + public boolean hasName() { + return true; + } + + public boolean hasNext() throws XMLStreamException { + return currentState != END_ELEMENT_STATE; + + } + + public boolean hasText() { + return false; + } + + public void init() { + // NOOP + } + + public boolean isAttributeSpecified(int i) { + return i == 0; + } + + public boolean isCharacters() { + return false; + } + + public boolean isDone() { + return currentState == END_ELEMENT_STATE; + } + + public boolean isEndElement() { + return currentState == END_ELEMENT_STATE; + } + + public boolean isStandalone() { + throw new UnsupportedOperationException(); + } + + public boolean isStartElement() { + return currentState == START_ELEMENT_STATE; + } + + public boolean isWhiteSpace() { + return false; + } + + public int next() throws XMLStreamException { + int returnEvent = START_DOCUMENT; + switch (currentState) { + case START_ELEMENT_STATE: + currentState = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + break; + case END_ELEMENT_STATE: + throw new XMLStreamException("parser completed!"); + + } + return returnEvent; + } + + public int nextTag() throws XMLStreamException { + throw new UnsupportedOperationException(); + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // nothing + } + + public boolean standaloneSet() { + throw new UnsupportedOperationException(); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.java new file mode 100644 index 0000000000..3e20e0be70 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.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.tuscany.sca.databinding.xml; + +import java.io.OutputStream; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +/** + * Push DOM Node to OutputStream + */ +public class Node2OutputStream extends BaseTransformer<Node, OutputStream> implements + PushTransformer<Node, OutputStream> { + private static final Source2ResultTransformer TRANSFORMER = new Source2ResultTransformer(); + + public void transform(Node source, OutputStream writer, TransformationContext context) { + try { + Source domSource = new DOMSource(source); + Result result = new StreamResult(writer); + TRANSFORMER.transform(domSource, result, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Node.class; + } + + @Override + public Class getTargetType() { + return OutputStream.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.java new file mode 100644 index 0000000000..f20cd4f901 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.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.tuscany.sca.databinding.xml; + +import org.apache.tuscany.sca.databinding.impl.SimpleType2JavaTransformer; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Transformer to convert data from a simple java bject to OMElement + */ +public class Node2SimpleJavaType extends SimpleType2JavaTransformer<Node> { + + @Override + protected String getText(Node source) { + if (source instanceof Document) { + source = ((Document)source).getDocumentElement(); + } + return source.getTextContent(); + + } + + @Override + public Class getSourceType() { + return Node.class; + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.java new file mode 100755 index 0000000000..b07e6eb955 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.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.tuscany.sca.databinding.xml; + +import java.io.StringWriter; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +/** + * Transform DOM Node to XML String + */ +public class Node2String extends BaseTransformer<Node, String> implements PullTransformer<Node, String> { + private static final Node2Writer TRANSFORMER = new Node2Writer(); + + public String transform(Node source, TransformationContext context) { + try { + StringWriter writer = new StringWriter(); + TRANSFORMER.transform(source, writer, context); + return writer.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Node.class; + } + + @Override + public Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.java new file mode 100644 index 0000000000..2b26c11d50 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.io.Writer; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +/** + * Push DOM Node to Writer + */ +public class Node2Writer extends BaseTransformer<Node, Writer> implements PushTransformer<Node, Writer> { + private static final Source2ResultTransformer TRANSFORMER = new Source2ResultTransformer(); + + public void transform(Node source, Writer writer, TransformationContext context) { + try { + Source domSource = new DOMSource(source); + Result result = new StreamResult(writer); + TRANSFORMER.transform(domSource, result, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Node.class; + } + + @Override + public Class getTargetType() { + return Writer.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.java new file mode 100644 index 0000000000..e611b0d09d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +/** + * Transform DOM Node to XML XMLStreamReader + */ +public class Node2XMLStreamReader extends BaseTransformer<Node, XMLStreamReader> implements + PullTransformer<Node, XMLStreamReader> { + + public XMLStreamReader transform(Node source, TransformationContext context) { + try { + DOMXMLStreamReader reader = new DOMXMLStreamReader(source); + return new XMLDocumentStreamReader(reader); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Node.class; + } + + @Override + public Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.java new file mode 100644 index 0000000000..aa96877c02 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.io.Reader; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +/** + * Push DOM Reader to Node + */ +public class Reader2Node extends BaseTransformer<Reader, Node> implements PullTransformer<Reader, Node> { + private static final Source2ResultTransformer TRANSFORMER = new Source2ResultTransformer(); + + public Node transform(Reader source, TransformationContext context) { + try { + Source streamSource = new StreamSource(source); + DOMResult result = new DOMResult(); + TRANSFORMER.transform(streamSource, result, context); + return result.getNode(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Reader.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.java new file mode 100644 index 0000000000..bf8edc47f9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.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.tuscany.sca.databinding.xml; + +import java.io.Reader; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; + +/** + * Transform XML string to SAX + */ +public class Reader2SAX extends BaseTransformer<Reader, ContentHandler> implements + PushTransformer<Reader, ContentHandler> { + public void transform(Reader source, ContentHandler target, TransformationContext context) { + try { + new InputSource2SAX().transform(new InputSource(source), target, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Reader.class; + } + + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOM.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOM.java new file mode 100644 index 0000000000..6cdbc82d9d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOM.java @@ -0,0 +1,244 @@ +/* + * Copyright 2001-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.tuscany.sca.databinding.xml; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Comment; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; +import org.w3c.dom.Text; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +/** + * SAX2DOM adapter + */ +public class SAX2DOM implements ContentHandler, LexicalHandler { + public static final String EMPTYSTRING = ""; + public static final String XML_PREFIX = "xml"; + public static final String XMLNS_PREFIX = "xmlns"; + public static final String XMLNS_STRING = "xmlns:"; + public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; + + private Node root; + + private Document document; + + private Node nextSibling; + + private Stack<Node> nodeStk = new Stack<Node>(); + + private List<String> namespaceDecls; + + private Node lastSibling; + + public SAX2DOM() throws ParserConfigurationException { + this.document = DOMHelper.newDocument(); + this.root = document; + } + + public SAX2DOM(Node root, Node nextSibling) throws ParserConfigurationException { + this.root = root; + if (root instanceof Document) { + this.document = (Document)root; + } else if (root != null) { + this.document = root.getOwnerDocument(); + } else { + this.document = DOMHelper.newDocument(); + this.root = document; + } + + this.nextSibling = nextSibling; + } + + public SAX2DOM(Node root) throws ParserConfigurationException { + this(root, null); + } + + public Node getDOM() { + return root; + } + + public void characters(char[] ch, int start, int length) { + final Node last = nodeStk.peek(); + + // No text nodes can be children of root (DOM006 exception) + if (last != document) { + final String text = new String(ch, start, length); + if (lastSibling != null && lastSibling.getNodeType() == Node.TEXT_NODE) { + ((Text)lastSibling).appendData(text); + } else if (last == root && nextSibling != null) { + lastSibling = last.insertBefore(document.createTextNode(text), nextSibling); + } else { + lastSibling = last.appendChild(document.createTextNode(text)); + } + + } + } + + public void startDocument() { + nodeStk.push(root); + } + + public void endDocument() { + nodeStk.pop(); + } + + public void startElement(String namespace, String localName, String qName, Attributes attrs) { + final Element tmp = document.createElementNS(namespace, qName); + + // Add namespace declarations first + if (namespaceDecls != null) { + final int nDecls = namespaceDecls.size(); + for (int i = 0; i < nDecls; i++) { + final String prefix = namespaceDecls.get(i++); + + if (prefix == null || prefix.equals(EMPTYSTRING)) { + tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX, namespaceDecls.get(i)); + } else { + tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix, namespaceDecls.get(i)); + } + } + namespaceDecls.clear(); + } + + // Add attributes to element + final int nattrs = attrs.getLength(); + for (int i = 0; i < nattrs; i++) { + if (attrs.getLocalName(i) == null) { + tmp.setAttribute(attrs.getQName(i), attrs.getValue(i)); + } else { + tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i), attrs.getValue(i)); + } + } + + // Append this new node onto current stack node + Node last = nodeStk.peek(); + + // If the SAX2DOM is created with a non-null next sibling node, + // insert the result nodes before the next sibling under the root. + if (last == root && nextSibling != null) { + last.insertBefore(tmp, nextSibling); + } else { + last.appendChild(tmp); + } + + // Push this node onto stack + nodeStk.push(tmp); + lastSibling = null; + } + + public void endElement(String namespace, String localName, String qName) { + nodeStk.pop(); + lastSibling = null; + } + + public void startPrefixMapping(String prefix, String uri) { + if (namespaceDecls == null) { + namespaceDecls = new ArrayList<String>(2); + } + namespaceDecls.add(prefix); + namespaceDecls.add(uri); + } + + public void endPrefixMapping(String prefix) { + // do nothing + } + + /** + * This class is only used internally so this method should never be called. + */ + public void ignorableWhitespace(char[] ch, int start, int length) { + } + + /** + * adds processing instruction node to DOM. + */ + public void processingInstruction(String target, String data) { + final Node last = nodeStk.peek(); + ProcessingInstruction pi = document.createProcessingInstruction(target, data); + if (pi != null) { + if (last == root && nextSibling != null) { + last.insertBefore(pi, nextSibling); + } else { + last.appendChild(pi); + } + + lastSibling = pi; + } + } + + /** + * This class is only used internally so this method should never be called. + */ + public void setDocumentLocator(Locator locator) { + } + + /** + * This class is only used internally so this method should never be called. + */ + public void skippedEntity(String name) { + } + + /** + * Lexical Handler method to create comment node in DOM tree. + */ + public void comment(char[] ch, int start, int length) { + final Node last = nodeStk.peek(); + Comment comment = document.createComment(new String(ch, start, length)); + if (comment != null) { + if (last == root && nextSibling != null) { + last.insertBefore(comment, nextSibling); + } else { + last.appendChild(comment); + } + + lastSibling = comment; + } + } + + // Lexical Handler methods- not implemented + public void startCDATA() { + } + + public void endCDATA() { + } + + public void startEntity(java.lang.String name) { + } + + public void endDTD() { + } + + public void endEntity(String name) { + } + + public void startDTD(String name, String publicId, String systemId) throws SAXException { + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.java new file mode 100644 index 0000000000..35c20c28c0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.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.tuscany.sca.databinding.xml; + +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +public class SAX2DOMPipe extends BaseTransformer<ContentHandler, Node> implements DataPipeTransformer<ContentHandler, Node> { + + /** + * + */ + public SAX2DOMPipe() { + super(); + } + + /** + * @see org.apache.tuscany.sca.databinding.DataPipeTransformer#newInstance() + */ + public DataPipe<ContentHandler, Node> newInstance() { + return new Pipe(); + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public Class getSourceType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 30; + } + + private static class Pipe implements DataPipe<ContentHandler, Node> { + private SAX2DOM pipe; + + public Pipe() { + super(); + try { + this.pipe = new SAX2DOM(); + } catch (ParserConfigurationException e) { + throw new IllegalArgumentException(e); + } + } + + public Node getResult() { + return pipe.getDOM(); + } + + public ContentHandler getSink() { + return pipe; + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.java new file mode 100644 index 0000000000..486f1f256a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.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.tuscany.sca.databinding.xml; + +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.apache.tuscany.sca.databinding.impl.Java2SimpleTypeTransformer; +import org.apache.tuscany.sca.databinding.javabeans.Java2XMLMapperException; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Transformer to convert data from an simple OMElement to Java Object + */ +public class SimpleJavaType2Node extends Java2SimpleTypeTransformer<Node> { + + private Document factory; + + public SimpleJavaType2Node() { + super(); + try { + factory = DOMHelper.newDocument(); + } catch (ParserConfigurationException e) { + throw new Java2XMLMapperException(e); + } + } + + @Override + protected Node createElement(QName element, String text, TransformationContext context) { + if (element == null) { + element = DOMDataBinding.ROOT_ELEMENT; + } + Node root = DOMHelper.createElement(factory, element); + if (text != null) { + root.appendChild(factory.createTextNode(text)); + } else { + Attr nil = factory.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil"); + nil.setValue("true"); + root.appendChild(nil); + } + return root; + } + + @Override + public Class getTargetType() { + return Node.class; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.java new file mode 100755 index 0000000000..b502b5003f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +/** + * Transform TrAX Source to Result + */ +public class Source2ResultTransformer extends BaseTransformer<Source, Result> implements + PushTransformer<Source, Result> { + private static final TransformerFactory FACTORY = TransformerFactory.newInstance(); + + public void transform(Source source, Result result, TransformationContext context) { + try { + javax.xml.transform.Transformer transformer = FACTORY.newTransformer(); + transformer.transform(source, result); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Source.class; + } + + @Override + public Class getTargetType() { + return Result.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAX2SAXAdapter.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAX2SAXAdapter.java new file mode 100644 index 0000000000..6257681091 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAX2SAXAdapter.java @@ -0,0 +1,256 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +/** + * Adapter that converts from StAX to SAX event streams. Currently the following + * SAX events are not generated: + * <ul> + * <li>ignorableWhitespace</li> + * <li>skippedEntity</li> + * <ul> + * Also the following StAX events are not mapped: + * <ul> + * <li>CDATA</li> + * <li>COMMENT</li> + * <li>DTD</li> + * <li>ENTITY_DECLARATION</li> + * <li>ENTITY_REFERENCE</li> + * <li>NOTATION_DECLARATION</li> + * <li>SPACE</li> + * </ul> + * StAX ATTRIBUTE events are ignored but the equivalent attributes (derived from + * the START_ELEMENT event) are supplied in the SAX startElement event's + * Attributes parameter. If the adaptor is configured to pass namespace prefixes + * then namespace information will also be included in the Attributes; StAX + * NAMESPACE events are ignored. <p/> Another issue is namespace processing. If + * the reader is positioned at a sub-node, we cannot capture all the in-scope + * namespace bindings. Therefore we cannot re-create a proper SAX event stream + * from a StAX parser. <p/> For example <p/> <a:root xmlns:a="foo" + * xmlns:b="bar"><b:sub>a:foo</b:sub></a:root> <p/> And if + * you are handed a parser at <b:sub>, then your SAX events should look + * like: <p/> <b:sub xmlns:a="foo" xmlns:b="bar">a:foo</b:sub> <p/> + * not: <p/> <b:sub>a:foo</b:sub> <p/> <p/> Proposal: we change the + * receiver of SAX events (SDOXMLResourceImpl) so that it uses NamespaceContext + * to resolve prefix (as opposed to record start/endPrefixMappings and use it + * for resolution.) + * + * @version $Rev$ $Date$ + */ +public class StAX2SAXAdapter { + private final boolean namespacePrefixes; + + /** + * Construct a new StAX to SAX adapter that will convert a StAX event stream + * into a SAX event stream. + * + * @param namespacePrefixes whether xmlns attributes should be included in + * startElement events; + */ + public StAX2SAXAdapter(boolean namespacePrefixes) { + this.namespacePrefixes = namespacePrefixes; + } + + /** + * Pull events from the StAX stream and dispatch to the SAX ContentHandler. + * The StAX stream would typically be located on a START_DOCUMENT or + * START_ELEMENT event and when this method returns it will be located on + * the associated END_DOCUMENT or END_ELEMENT event. Behaviour with other + * start events is undefined. + * + * @param reader StAX event source to read + * @param handler SAX ContentHandler for processing events + * @throws XMLStreamException if there was a problem reading the stream + * @throws SAXException passed through from the ContentHandler + */ + public void parse(XMLStreamReader reader, ContentHandler handler) throws XMLStreamException, SAXException { + handler.setDocumentLocator(new LocatorAdaptor(reader.getLocation())); + + // remembers the nest level of elements to know when we are done + int level = 0; + int event = reader.getEventType(); + while (true) { + switch (event) { + case XMLStreamConstants.START_DOCUMENT: + level++; + handler.startDocument(); + break; + case XMLStreamConstants.START_ELEMENT: + level++; + handleStartElement(reader, handler); + break; + case XMLStreamConstants.PROCESSING_INSTRUCTION: + handler.processingInstruction(reader.getPITarget(), reader.getPIData()); + break; + case XMLStreamConstants.CHARACTERS: + handler.characters(reader.getTextCharacters(), reader.getTextStart(), reader + .getTextLength()); + break; + case XMLStreamConstants.END_ELEMENT: + handleEndElement(reader, handler); + level--; + if (level == 0) { + return; + } + break; + case XMLStreamConstants.END_DOCUMENT: + handler.endDocument(); + return; + /* + * uncomment to handle all events rather than just mapped + * ones // StAX events that are not mapped to SAX case + * XMLStreamConstants.COMMENT: case + * XMLStreamConstants.SPACE: case + * XMLStreamConstants.ENTITY_REFERENCE: case + * XMLStreamConstants.DTD: case XMLStreamConstants.CDATA: + * case XMLStreamConstants.NOTATION_DECLARATION: case + * XMLStreamConstants.ENTITY_DECLARATION: break; // StAX + * events handled in START_ELEMENT case + * XMLStreamConstants.ATTRIBUTE: case + * XMLStreamConstants.NAMESPACE: break; default: throw new + * AssertionError("Unknown StAX event: " + event); + */ + } + event = reader.next(); + } + } + + private void handleStartElement(XMLStreamReader reader, ContentHandler handler) throws SAXException { + // send startPrefixMapping events immediately before startElement event + int nsCount = reader.getNamespaceCount(); + for (int i = 0; i < nsCount; i++) { + String prefix = reader.getNamespacePrefix(i); + if (prefix == null) { // true for default namespace + prefix = ""; + } + handler.startPrefixMapping(prefix, reader.getNamespaceURI(i)); + } + + // fire startElement + QName qname = reader.getName(); + String prefix = qname.getPrefix(); + String rawname; + if (prefix == null || prefix.length() == 0) { + rawname = qname.getLocalPart(); + } else { + rawname = prefix + ':' + qname.getLocalPart(); + } + Attributes attrs = getAttributes(reader); + handler.startElement(qname.getNamespaceURI(), qname.getLocalPart(), rawname, attrs); + } + + private static void handleEndElement(XMLStreamReader reader, ContentHandler handler) throws SAXException { + // fire endElement + QName qname = reader.getName(); + handler.endElement(qname.getNamespaceURI(), qname.getLocalPart(), qname.toString()); + + // send endPrefixMapping events immediately after endElement event + // we send them in the opposite order to that returned but this is not + // actually required by SAX + int nsCount = reader.getNamespaceCount(); + for (int i = nsCount - 1; i >= 0; i--) { + String prefix = reader.getNamespacePrefix(i); + if (prefix == null) { // true for default namespace + prefix = ""; + } + handler.endPrefixMapping(prefix); + } + } + + /** + * Get the attributes associated with the current START_ELEMENT event. + * + * @return the StAX attributes converted to org.xml.sax.Attributes + */ + private Attributes getAttributes(XMLStreamReader reader) { + assert reader.getEventType() == XMLStreamConstants.START_ELEMENT; + + AttributesImpl attrs = new AttributesImpl(); + + // add namespace declarations if required + if (namespacePrefixes) { + for (int i = 0; i < reader.getNamespaceCount(); i++) { + String prefix = reader.getNamespacePrefix(i); + String uri = reader.getNamespaceURI(i); + attrs.addAttribute(null, prefix, "xmlns:" + prefix, "CDATA", uri); + } + } + + // Regular attributes + for (int i = 0; i < reader.getAttributeCount(); i++) { + String uri = reader.getAttributeNamespace(i); + if (uri == null) { + uri = ""; + } + String localName = reader.getAttributeLocalName(i); + String prefix = reader.getAttributePrefix(i); + String qname; + if (prefix == null || prefix.length() == 0) { + qname = localName; + } else { + qname = prefix + ':' + localName; + } + String type = reader.getAttributeType(i); + String value = reader.getAttributeValue(i); + + attrs.addAttribute(uri, localName, qname, type, value); + } + + return attrs; + } + + /** + * Adaptor for mapping Locator information. + */ + private static final class LocatorAdaptor implements Locator { + private final Location location; + + private LocatorAdaptor(Location location) { + this.location = location; + } + + public int getColumnNumber() { + return location == null ? 0 : location.getColumnNumber(); + } + + public int getLineNumber() { + return location == null ? 0 : location.getLineNumber(); + } + + public String getPublicId() { + return location == null ? "" : location.getPublicId(); + } + + public String getSystemId() { + return location == null ? "" : location.getSystemId(); + } + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.java new file mode 100644 index 0000000000..57b02204e3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.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.tuscany.sca.databinding.xml; + +import java.lang.annotation.Annotation; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * A DataBinding for the StAX + * + * @version $Rev$ $Date$ + */ +public class StAXDataBinding extends BaseDataBinding { + public static final String NAME = XMLStreamReader.class.getName(); + public static final String[] ALIASES = new String[] {"stax"}; + + public StAXDataBinding() { + super(NAME, ALIASES, XMLStreamReader.class); + } + + @Override + public boolean introspect(DataType type, Annotation[] annotations) { + if (super.introspect(type, annotations)) { + type.setLogical(XMLType.UNKNOWN); + return true; + } else { + return false; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXHelper.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXHelper.java new file mode 100755 index 0000000000..103ecbd7d1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXHelper.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.tuscany.sca.databinding.xml; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.Source; + + +public final class StAXHelper { + private static final XMLInputFactory INPUT_FACTORY = XMLInputFactory.newInstance(); + private static final XMLOutputFactory OUTPUT_FACTORY = XMLOutputFactory.newInstance(); + + private StAXHelper() { + } + + public static XMLStreamReader createXMLStreamReader(InputStream inputStream) throws XMLStreamException { + return INPUT_FACTORY.createXMLStreamReader(inputStream); + } + + public static XMLStreamReader createXMLStreamReader(Reader reader) throws XMLStreamException { + return INPUT_FACTORY.createXMLStreamReader(reader); + } + + public static XMLStreamReader createXMLStreamReader(Source source) throws XMLStreamException { + return INPUT_FACTORY.createXMLStreamReader(source); + } + + public static XMLStreamReader createXMLStreamReader(String string) throws XMLStreamException { + StringReader reader = new StringReader(string); + return createXMLStreamReader(reader); + } + + public static String save(XMLStreamReader reader) throws XMLStreamException { + StringWriter writer = new StringWriter(); + save(reader, writer); + return writer.toString(); + } + + public static void save(XMLStreamReader reader, OutputStream outputStream) throws XMLStreamException { + XMLStreamSerializer serializer = new XMLStreamSerializer(); + XMLStreamWriter streamWriter = OUTPUT_FACTORY.createXMLStreamWriter(outputStream); + serializer.serialize(reader, streamWriter); + streamWriter.flush(); + } + + public static void save(XMLStreamReader reader, Writer writer) throws XMLStreamException { + XMLStreamSerializer serializer = new XMLStreamSerializer(); + XMLStreamWriter streamWriter = OUTPUT_FACTORY.createXMLStreamWriter(writer); + serializer.serialize(reader, streamWriter); + streamWriter.flush(); + } + + public static void save(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + XMLStreamSerializer serializer = new XMLStreamSerializer(); + serializer.serialize(reader, writer); + writer.flush(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.java new file mode 100755 index 0000000000..f5fd229ae5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +public class StreamDataPipe extends BaseTransformer<OutputStream, InputStream> implements + DataPipeTransformer<OutputStream, InputStream> { + + public DataPipe<OutputStream, InputStream> newInstance() { + return new Pipe(); + } + + @Override + public Class getTargetType() { + return InputStream.class; + } + + @Override + public int getWeight() { + return 50; + } + + @Override + public Class getSourceType() { + return OutputStream.class; + } + + public static class Pipe implements DataPipe<OutputStream, InputStream> { + private ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + public InputStream getResult() { + return new ByteArrayInputStream(outputStream.toByteArray()); + } + + public OutputStream getSink() { + return outputStream; + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.java new file mode 100755 index 0000000000..902fddc234 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.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.tuscany.sca.databinding.xml; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +public class String2Node extends BaseTransformer<String, Node> implements PullTransformer<String, Node> { + + public Node transform(String source, TransformationContext context) { + try { + DocumentBuilder builder = DOMHelper.newDocumentBuilder(); + InputSource inputSource = new InputSource(new StringReader(source)); + return builder.parse(inputSource); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return String.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.java new file mode 100644 index 0000000000..776bae535c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.io.StringReader; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; + +/** + * Transform XML string to SAX + */ +public class String2SAX extends BaseTransformer<String, ContentHandler> implements + PushTransformer<String, ContentHandler> { + + public void transform(String source, ContentHandler target, TransformationContext context) { + try { + new InputSource2SAX().transform(new InputSource(new StringReader(source)), target, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return String.class; + } + + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.java new file mode 100755 index 0000000000..6dc78eefdb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.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.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +public class String2XMLStreamReader extends BaseTransformer<String, XMLStreamReader> implements + PullTransformer<String, XMLStreamReader> { + + public XMLStreamReader transform(String source, TransformationContext context) { + try { + return StAXHelper.createXMLStreamReader(source); + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return String.class; + } + + @Override + public Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/WrappingXMLStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/WrappingXMLStreamReader.java new file mode 100644 index 0000000000..dbf5de55cd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/WrappingXMLStreamReader.java @@ -0,0 +1,230 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +public class WrappingXMLStreamReader implements XMLFragmentStreamReader { + + private XMLStreamReader reader; + + public WrappingXMLStreamReader(XMLStreamReader reader) { + this.reader = reader; + } + + public boolean isDone() { + try { + return !hasNext(); + } catch (XMLStreamException e) { + throw new RuntimeException(e); + } + } + + public Object getProperty(String string) throws IllegalArgumentException { + return reader.getProperty(string); + } + + public int next() throws XMLStreamException { + return reader.next(); + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // nothing to do + } + + public String getElementText() throws XMLStreamException { + return reader.getElementText(); + } + + public int nextTag() throws XMLStreamException { + return reader.nextTag(); + } + + public boolean hasNext() throws XMLStreamException { + return reader.hasNext(); + } + + public void close() throws XMLStreamException { + reader.close(); + } + + public String getNamespaceURI(String string) { + return reader.getNamespaceURI(string); + } + + public boolean isStartElement() { + return reader.isStartElement(); + } + + public boolean isEndElement() { + return reader.isEndElement(); + } + + public boolean isCharacters() { + return reader.isCharacters(); + } + + public boolean isWhiteSpace() { + return reader.isWhiteSpace(); + } + + public String getAttributeValue(String string, String string1) { + return reader.getAttributeValue(string, string1); + } + + public int getAttributeCount() { + return reader.getAttributeCount(); + } + + public QName getAttributeName(int i) { + return reader.getAttributeName(i); + } + + public String getAttributeNamespace(int i) { + return reader.getAttributeNamespace(i); + } + + public String getAttributeLocalName(int i) { + return reader.getAttributeLocalName(i); + } + + public String getAttributePrefix(int i) { + return reader.getAttributeLocalName(i); + } + + public String getAttributeType(int i) { + return reader.getAttributeType(i); + } + + public String getAttributeValue(int i) { + return reader.getAttributeValue(i); + } + + public boolean isAttributeSpecified(int i) { + return reader.isAttributeSpecified(i); + } + + public int getNamespaceCount() { + return reader.getNamespaceCount(); + } + + public String getNamespacePrefix(int i) { + return reader.getNamespacePrefix(i); + } + + public String getNamespaceURI(int i) { + return reader.getNamespaceURI(i); + } + + public NamespaceContext getNamespaceContext() { + return reader.getNamespaceContext(); + } + + public int getEventType() { + return reader.getEventType(); + } + + public String getText() { + return reader.getText(); + } + + public char[] getTextCharacters() { + return reader.getTextCharacters(); + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + return reader.getTextCharacters(i, chars, i1, i2); + } + + public int getTextStart() { + return reader.getTextStart(); + } + + public int getTextLength() { + return reader.getTextLength(); + } + + public String getEncoding() { + return reader.getEncoding(); + } + + public boolean hasText() { + return reader.hasText(); + } + + public Location getLocation() { + return reader.getLocation(); + } + + public QName getName() { + return reader.getName(); + } + + public String getLocalName() { + return reader.getLocalName(); + } + + public boolean hasName() { + return reader.hasName(); + } + + public String getNamespaceURI() { + return reader.getNamespaceURI(); + } + + public String getPrefix() { + return reader.getPrefix(); + } + + public String getVersion() { + return reader.getVersion(); + } + + public boolean isStandalone() { + return reader.isStandalone(); + } + + public boolean standaloneSet() { + return reader.standaloneSet(); + } + + public String getCharacterEncodingScheme() { + return reader.getCharacterEncodingScheme(); + } + + public String getPITarget() { + return reader.getPITarget(); + } + + public String getPIData() { + return reader.getPIData(); + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + // nothing to do here + } + + public void init() { + // Nothing to do here + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.java new file mode 100755 index 0000000000..3ec97a9049 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.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.tuscany.sca.databinding.xml; + +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +public class Writer2ReaderDataPipe extends BaseTransformer<Writer, Reader> implements DataPipeTransformer<Writer, Reader> { + + public DataPipe<Writer, Reader> newInstance() { + return new Pipe(); + } + + @Override + public Class getTargetType() { + return Reader.class; + } + + @Override + public int getWeight() { + return 50; + } + + @Override + public Class getSourceType() { + return Writer.class; + } + + private static class Pipe implements DataPipe<Writer, Reader> { + private StringWriter writer = new StringWriter(); + + public Reader getResult() { + return new StringReader(writer.toString()); + } + + public Writer getSink() { + return writer; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLDocumentStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLDocumentStreamReader.java new file mode 100644 index 0000000000..e2bebd0eb0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLDocumentStreamReader.java @@ -0,0 +1,451 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.xml; + +import java.util.NoSuchElementException; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +/** + * This class is derived from Apache Axis2 class + * org.apache.axis2.util.StreamWrapper</a>. It's used wrap a XMLStreamReader to + * create a XMLStreamReader representing a document and it will produce + * START_DOCUMENT, END_DOCUMENT events. + */ +public class XMLDocumentStreamReader implements XMLStreamReader { + private static final int STATE_COMPLETE_AT_NEXT = 2; // The wrapper + // will produce + // END_DOCUMENT + + private static final int STATE_COMPLETED = 3; // Done + + private static final int STATE_INIT = 0; // The wrapper will produce + // START_DOCUMENT + + private static final int STATE_SWITCHED = 1; // The real reader will + // produce events + + private XMLStreamReader realReader; + + private int state = STATE_INIT; + + public XMLDocumentStreamReader(XMLStreamReader realReader) { + if (realReader == null) { + throw new UnsupportedOperationException("Reader cannot be null"); + } + + this.realReader = realReader; + + if (realReader instanceof XMLFragmentStreamReader) { + ((XMLFragmentStreamReader)realReader).init(); + } + + // If the real reader is positioned at START_DOCUMENT, always use + // the real reader + if (realReader.getEventType() == START_DOCUMENT) { + state = STATE_SWITCHED; + } + } + + public void close() throws XMLStreamException { + realReader.close(); + } + + public int getAttributeCount() { + if (isDelegating()) { + return realReader.getAttributeCount(); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeLocalName(int i) { + if (isDelegating()) { + return realReader.getAttributeLocalName(i); + } else { + throw new IllegalStateException(); + } + } + + public QName getAttributeName(int i) { + if (isDelegating()) { + return realReader.getAttributeName(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeNamespace(int i) { + if (isDelegating()) { + return realReader.getAttributeNamespace(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributePrefix(int i) { + if (isDelegating()) { + return realReader.getAttributePrefix(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeType(int i) { + if (isDelegating()) { + return realReader.getAttributeType(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeValue(int i) { + if (isDelegating()) { + return realReader.getAttributeValue(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeValue(String s, String s1) { + if (isDelegating()) { + return realReader.getAttributeValue(s, s1); + } else { + throw new IllegalStateException(); + } + } + + public String getCharacterEncodingScheme() { + return realReader.getCharacterEncodingScheme(); + } + + public String getElementText() throws XMLStreamException { + if (isDelegating()) { + return realReader.getElementText(); + } else { + throw new XMLStreamException(); + } + } + + public String getEncoding() { + return realReader.getEncoding(); + } + + public int getEventType() { + int event = -1; + switch (state) { + case STATE_SWITCHED: + case STATE_COMPLETE_AT_NEXT: + event = realReader.getEventType(); + break; + case STATE_INIT: + event = START_DOCUMENT; + break; + case STATE_COMPLETED: + event = END_DOCUMENT; + break; + } + return event; + } + + public String getLocalName() { + if (isDelegating()) { + return realReader.getLocalName(); + } else { + throw new IllegalStateException(); + } + } + + public Location getLocation() { + if (isDelegating()) { + return realReader.getLocation(); + } else { + return null; + } + } + + public QName getName() { + if (isDelegating()) { + return realReader.getName(); + } else { + throw new IllegalStateException(); + } + } + + public NamespaceContext getNamespaceContext() { + return realReader.getNamespaceContext(); + } + + public int getNamespaceCount() { + if (isDelegating()) { + return realReader.getNamespaceCount(); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespacePrefix(int i) { + if (isDelegating()) { + return realReader.getNamespacePrefix(i); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespaceURI() { + if (isDelegating()) { + return realReader.getNamespaceURI(); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespaceURI(int i) { + if (isDelegating()) { + return realReader.getNamespaceURI(i); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespaceURI(String s) { + if (isDelegating()) { + return realReader.getNamespaceURI(s); + } else { + throw new IllegalStateException(); + } + } + + public String getPIData() { + if (isDelegating()) { + return realReader.getPIData(); + } else { + throw new IllegalStateException(); + } + } + + public String getPITarget() { + if (isDelegating()) { + return realReader.getPITarget(); + } else { + throw new IllegalStateException(); + } + } + + public String getPrefix() { + if (isDelegating()) { + return realReader.getPrefix(); + } else { + throw new IllegalStateException(); + } + } + + public Object getProperty(String s) throws IllegalArgumentException { + if (isDelegating()) { + return realReader.getProperty(s); + } else { + throw new IllegalArgumentException(); + } + } + + public String getText() { + if (isDelegating()) { + return realReader.getText(); + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (isDelegating()) { + return realReader.getTextCharacters(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + if (isDelegating()) { + return realReader.getTextCharacters(i, chars, i1, i2); + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (isDelegating()) { + return realReader.getTextLength(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextStart() { + if (isDelegating()) { + return realReader.getTextStart(); + } else { + throw new IllegalStateException(); + } + } + + public String getVersion() { + if (isDelegating()) { + return realReader.getVersion(); + } else { + return null; + } + } + + public boolean hasName() { + if (isDelegating()) { + return realReader.hasName(); + } else { + return false; + } + } + + public boolean hasNext() throws XMLStreamException { + if (state == STATE_COMPLETE_AT_NEXT) { + return true; + } else if (state == STATE_COMPLETED) { + return false; + } else if (state == STATE_SWITCHED) { + return realReader.hasNext(); + } else { + return true; + } + } + + public boolean hasText() { + if (isDelegating()) { + return realReader.hasText(); + } else { + return false; + } + } + + public boolean isAttributeSpecified(int i) { + if (isDelegating()) { + return realReader.isAttributeSpecified(i); + } else { + return false; + } + } + + public boolean isCharacters() { + if (isDelegating()) { + return realReader.isCharacters(); + } else { + return false; + } + } + + private boolean isDelegating() { + return state == STATE_SWITCHED || state == STATE_COMPLETE_AT_NEXT; + } + + public boolean isEndElement() { + if (isDelegating()) { + return realReader.isEndElement(); + } else { + return false; + } + } + + public boolean isStandalone() { + if (isDelegating()) { + return realReader.isStandalone(); + } else { + return false; + } + } + + public boolean isStartElement() { + if (isDelegating()) { + return realReader.isStartElement(); + } else { + return false; + } + } + + public boolean isWhiteSpace() { + if (isDelegating()) { + return realReader.isWhiteSpace(); + } else { + return false; + } + } + + public int next() throws XMLStreamException { + int returnEvent; + + switch (state) { + case STATE_SWITCHED: + returnEvent = realReader.next(); + if (returnEvent == END_DOCUMENT) { + state = STATE_COMPLETED; + } else if (!realReader.hasNext()) { + state = STATE_COMPLETE_AT_NEXT; + } + break; + case STATE_INIT: + state = STATE_SWITCHED; + returnEvent = realReader.getEventType(); + break; + case STATE_COMPLETE_AT_NEXT: + state = STATE_COMPLETED; + returnEvent = END_DOCUMENT; + break; + case STATE_COMPLETED: + // oops - no way we can go beyond this + throw new NoSuchElementException("End of stream has reached."); + default: + throw new UnsupportedOperationException(); + } + + return returnEvent; + } + + public int nextTag() throws XMLStreamException { + if (isDelegating()) { + return realReader.nextTag(); + } else { + throw new XMLStreamException(); + } + } + + public void require(int i, String s, String s1) throws XMLStreamException { + if (isDelegating()) { + realReader.require(i, s, s1); + } + } + + public boolean standaloneSet() { + if (isDelegating()) { + return realReader.standaloneSet(); + } else { + return false; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLFragmentStreamReader.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLFragmentStreamReader.java new file mode 100644 index 0000000000..a42d6acc9a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLFragmentStreamReader.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.tuscany.sca.databinding.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +public interface XMLFragmentStreamReader extends XMLStreamReader { + QName NIL_QNAME = new QName("http://www.w3.org/2001/XMLSchema-instance", "nil", "xsi"); + String NIL_VALUE_TRUE = "true"; + + /** + * this will help to handle Text within the current element. user should + * pass the element text to the property list as this ELEMENT_TEXT as the + * key. This key deliberately has a space in it so that it is not a valid + * XML name + */ + String ELEMENT_TEXT = "Element Text"; + + /** + * Extra method to query the state of the pullparser + */ + boolean isDone(); + + /** + * add the parent namespace context to this parser + */ + void setParentNamespaceContext(NamespaceContext nsContext); + + /** + * Initiate the parser - this will do whatever the needed tasks to initiate + * the parser and must be called before attempting any specific parsing + * using this parser + */ + void init(); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLFragmentStreamReaderImpl.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLFragmentStreamReaderImpl.java new file mode 100644 index 0000000000..07f3d0d111 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLFragmentStreamReaderImpl.java @@ -0,0 +1,857 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +/** + * This is the new implementation of the XMLFramentStreamReader. The approach + * here is simple When the pull parser needs to generate events for a particular + * name-value(s) pair it always handes over (delegates) the task to another pull + * parser which knows how to deal with it The common types of name value pairs + * we'll come across are + * <ul> + * <li> String name/QName name - String value + * <li> String name/QName name - String[] value + * <li> QName name/String name - XMLStreamReader value + * <li> QName name/String name - XMLStreamable value + * <li> QName name/String name - Java bean + * <li> QName name/String name - Datahandler + * + * </ul> + * <p/> As for the attributes, these are the possible combinations in the array + * <ul> + * <li> String name/QName name - String value + * </ul> + * Note that certain array methods have been deliberately removed to avoid + * complications. The generated code will take the trouble to lay the elements + * of the array in the correct order <p/> <p/> Hence there will be a parser impl + * that knows how to handle these types, and this parent parser will always + * delegate these tasks to the child pullparasers in effect this is one huge + * state machine that has only a few states and delegates things down to the + * child parsers whenever possible <p/> + * + * @version $Rev$ $Date$ + */ +public class XMLFragmentStreamReaderImpl implements XMLFragmentStreamReader { + + private static final int DELEGATED_STATE = 2; + private static final int END_ELEMENT_STATE = 1; + // states for this pullparser - it can only have four states + private static final int START_ELEMENT_STATE = 0; + private static final int TEXT_STATE = 3; + + protected NamedProperty[] attributes; + + // reference to the child reader + protected XMLFragmentStreamReader childReader; + // current property index + // initialized at zero + protected int index; + protected Map<String, String> declaredNamespaceMap = new HashMap<String, String>(); + protected QName elementQName; + + // we always create a new namespace context + protected DelegatingNamespaceContext namespaceContext = new DelegatingNamespaceContext(); + + protected NamedProperty[] elements; + + // integer field that keeps the state of this + // parser. + protected int state = START_ELEMENT_STATE; + + /* + * we need to pass in a namespace context since when delegated, we've no + * idea of the current namespace context. So it needs to be passed on here! + */ + public XMLFragmentStreamReaderImpl(QName elementQName, NamedProperty[] elements, NamedProperty[] attributes) { + // validate the lengths, since both the arrays are supposed + // to have + this.elements = elements == null ? new NamedProperty[0] : elements; + this.elementQName = elementQName; + this.attributes = attributes == null ? new NamedProperty[0] : attributes; + } + + protected XMLFragmentStreamReaderImpl(QName elementQName) { + this.elementQName = elementQName; + } + + /** + * add the namespace context + */ + + public void setParentNamespaceContext(NamespaceContext nsContext) { + // register the namespace context passed in to this + this.namespaceContext.setParentNsContext(nsContext); + + } + + protected NamedProperty[] getElements() { + return elements; + } + + protected NamedProperty[] getAttributes() { + return attributes; + } + + protected QName[] getNamespaces() { + return new QName[0]; + } + + /** + * @param prefix + * @param uri + */ + protected void addToNsMap(String prefix, String uri) { + if (!uri.equals(namespaceContext.getNamespaceURI(prefix))) { + namespaceContext.pushNamespace(prefix, uri); + declaredNamespaceMap.put(prefix, uri); + } + } + + public void close() throws XMLStreamException { + // do nothing here - we have no resources to free + } + + public int getAttributeCount() { + return (state == DELEGATED_STATE) ? childReader.getAttributeCount() : (state == START_ELEMENT_STATE + ? getAttributes().length : 0); + } + + public String getAttributeLocalName(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeLocalName(i); + } else if (state == START_ELEMENT_STATE) { + QName name = getAttributeName(i); + if (name == null) { + return null; + } else { + return name.getLocalPart(); + } + } else { + throw new IllegalStateException(); + } + } + + /** + * @param i + */ + public QName getAttributeName(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeName(i); + } else if (state == START_ELEMENT_STATE) { + if ((i >= (getAttributes().length)) || i < 0) { // out of range + return null; + } else { + // get the attribute pointer + QName attribPointer = getAttributes()[i].getKey(); + // case one - attrib name is null + // this should be the pointer to the OMAttribute then + if (attribPointer == null) { + throw new UnsupportedOperationException(); + } else if (attribPointer instanceof QName) { + return attribPointer; + } else { + return null; + } + } + } else { + throw new IllegalStateException(); // as per the api contract + } + + } + + public String getAttributeNamespace(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeNamespace(i); + } else if (state == START_ELEMENT_STATE) { + QName name = getAttributeName(i); + if (name == null) { + return null; + } else { + return name.getNamespaceURI(); + } + } else { + throw new IllegalStateException(); + } + } + + public String getAttributePrefix(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributePrefix(i); + } else if (state == START_ELEMENT_STATE) { + QName name = getAttributeName(i); + if (name == null) { + return null; + } else { + return name.getPrefix(); + } + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeType(int i) { + return null; // not supported + } + + public String getAttributeValue(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeValue(i); + } else if (state == START_ELEMENT_STATE) { + if ((i >= (getAttributes().length)) || i < 0) { // out of range + return null; + } else { + // get the attribute pointer + QName attribPointer = getAttributes()[i].getKey(); + Object omAttribObj = getAttributes()[i].getValue(); + // case one - attrib name is null + // this should be the pointer to the OMAttribute then + if (attribPointer == null) { + throw new UnsupportedOperationException(); + } else if (attribPointer instanceof QName) { + return (String)omAttribObj; + } else { + return null; + } + } + } else { + throw new IllegalStateException(); + } + + } + + public String getAttributeValue(String nsUri, String localName) { + + int attribCount = getAttributeCount(); + String returnValue = null; + QName attribQualifiedName; + for (int i = 0; i < attribCount; i++) { + attribQualifiedName = getAttributeName(i); + if (nsUri == null) { + if (localName.equals(attribQualifiedName.getLocalPart())) { + returnValue = getAttributeValue(i); + break; + } + } else { + if (localName.equals(attribQualifiedName.getLocalPart()) && nsUri.equals(attribQualifiedName + .getNamespaceURI())) { + returnValue = getAttributeValue(i); + break; + } + } + + } + + return returnValue; + } + + public String getCharacterEncodingScheme() { + return null; // todo - should we return something for this ? + } + + /** + * todo implement the right contract for this + * + * @throws XMLStreamException + */ + public String getElementText() throws XMLStreamException { + if (state == DELEGATED_STATE) { + return childReader.getElementText(); + } else { + return null; + } + + } + + // ///////////////////////////////////////////////////////////////////////// + // / attribute handling + // ///////////////////////////////////////////////////////////////////////// + + public String getEncoding() { + if (state == DELEGATED_STATE) { + return childReader.getEncoding(); + } else { + // we've no idea what the encoding is going to be in this case + // perhaps we ought to return some constant here, which the user + // might + // have access to change! + return null; + } + } + + public int getEventType() { + if (state == START_ELEMENT_STATE) { + return START_ELEMENT; + } else if (state == END_ELEMENT_STATE) { + return END_ELEMENT; + } else if (state == TEXT_STATE) { + return CHARACTERS; + } else { // this is the delegated state + return childReader.getEventType(); + } + } + + public String getLocalName() { + if (state == DELEGATED_STATE) { + return childReader.getLocalName(); + } else if (state != TEXT_STATE) { + return elementQName.getLocalPart(); + } else { + throw new IllegalStateException(); + } + } + + /** + */ + public Location getLocation() { + // return a default location + return new Location() { + public int getCharacterOffset() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getLineNumber() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + if (state == DELEGATED_STATE) { + return childReader.getName(); + } else if (state != TEXT_STATE) { + return elementQName; + } else { + throw new IllegalStateException(); + } + + } + + public NamespaceContext getNamespaceContext() { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceContext(); + } else { + return namespaceContext; + } + + } + + public int getNamespaceCount() { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceCount(); + } else { + return declaredNamespaceMap.size(); + } + } + + /** + * @param i + */ + public String getNamespacePrefix(int i) { + if (state == DELEGATED_STATE) { + return childReader.getNamespacePrefix(i); + } else if (state != TEXT_STATE) { + // order the prefixes + String[] prefixes = makePrefixArray(); + if ((i >= prefixes.length) || (i < 0)) { + return null; + } else { + return prefixes[i]; + } + + } else { + throw new IllegalStateException(); + } + + } + + public String getNamespaceURI() { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceURI(); + } else if (state == TEXT_STATE) { + return null; + } else { + return elementQName.getNamespaceURI(); + } + } + + // ///////////////////////////////////////////////////////////////////////// + // //////////// end of attribute handling + // ///////////////////////////////////////////////////////////////////////// + + // ////////////////////////////////////////////////////////////////////////// + // //////////// namespace handling + // ////////////////////////////////////////////////////////////////////////// + + public String getNamespaceURI(int i) { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceURI(i); + } else if (state != TEXT_STATE) { + String namespacePrefix = getNamespacePrefix(i); + return namespacePrefix == null ? null : (String)declaredNamespaceMap.get(namespacePrefix); + } else { + throw new IllegalStateException(); + } + + } + + public String getNamespaceURI(String prefix) { + return namespaceContext.getNamespaceURI(prefix); + } + + public String getPIData() { + throw new UnsupportedOperationException("Yet to be implemented !!"); + } + + public String getPITarget() { + throw new UnsupportedOperationException("Yet to be implemented !!"); + } + + public String getPrefix() { + if (state == DELEGATED_STATE) { + return childReader.getPrefix(); + } else if (state == TEXT_STATE) { + return null; + } else { + String prefix = elementQName.getPrefix(); + return "".equals(prefix) ? null : prefix; + } + } + + // ///////////////////////////////////////////////////////////////////////// + // /////// end of namespace handling + // ///////////////////////////////////////////////////////////////////////// + + /** + * @param key + * @throws IllegalArgumentException + */ + public Object getProperty(String key) throws IllegalArgumentException { + if (state == START_ELEMENT_STATE || state == END_ELEMENT_STATE) { + return null; + } else if (state == TEXT_STATE) { + return null; + } else if (state == DELEGATED_STATE) { + return childReader.getProperty(key); + } else { + return null; + } + + } + + public String getText() { + if (state == DELEGATED_STATE) { + return childReader.getText(); + } else if (state == TEXT_STATE) { + return (String)getElements()[index - 1].getValue(); + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (state == DELEGATED_STATE) { + return childReader.getTextCharacters(); + } else if (state == TEXT_STATE) { + return getElements()[index - 1].getValue() == null ? new char[0] : ((String)getElements()[index - 1] + .getValue()).toCharArray(); + } else { + throw new IllegalStateException(); + } + } + + private int copy(int sourceStart, char[] target, int targetStart, int length) { + char[] source = getTextCharacters(); + if (sourceStart > source.length) { + throw new IndexOutOfBoundsException("source start > source length"); + } + int sourceLen = source.length - sourceStart; + if (length > sourceLen) { + length = sourceLen; + } + System.arraycopy(source, sourceStart, target, targetStart, length); + return sourceLen; + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + if (state == DELEGATED_STATE) { + return childReader.getTextCharacters(i, chars, i1, i2); + } else if (state == TEXT_STATE) { + return copy(i, chars, i1, i2); + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (state == DELEGATED_STATE) { + return childReader.getTextLength(); + } else if (state == TEXT_STATE) { + return getTextCharacters().length; + } else { + throw new IllegalStateException(); + } + } + + public int getTextStart() { + if (state == DELEGATED_STATE) { + return childReader.getTextStart(); + } else if (state == TEXT_STATE) { + return 0; // assume text always starts at 0 + } else { + throw new IllegalStateException(); + } + } + + public String getVersion() { + return null; + } + + public boolean hasName() { + // since this parser always has a name, the hasname + // has to return true if we are still navigating this element + // if not we should ask the child reader for it. + if (state == DELEGATED_STATE) { + return childReader.hasName(); + } else { + return state != TEXT_STATE; + } + } + + /** + * @throws XMLStreamException + */ + public boolean hasNext() throws XMLStreamException { + if (state == DELEGATED_STATE) { + if (childReader.isDone()) { + // the child reader is done. We shouldn't be getting the + // hasnext result from the child pullparser then + return true; + } else { + return childReader.hasNext(); + } + } else { + return state == START_ELEMENT_STATE || state == TEXT_STATE; + + } + } + + /** + * check the validity of this implementation + */ + public boolean hasText() { + if (state == DELEGATED_STATE) { + return childReader.hasText(); + } else { + return state == TEXT_STATE; + } + + } + + /** + * we need to split out the calling to the populate namespaces seperately + * since this needs to be done *after* setting the parent namespace context. + * We cannot assume it will happen at construction! + */ + public void init() { + // here we have an extra issue to attend to. we need to look at the + // prefixes and uris (the combination) and populate a hashmap of + // namespaces. The hashmap of namespaces will be used to serve the + // namespace context + + populateNamespaceContext(); + } + + public boolean isAttributeSpecified(int i) { + return false; // not supported + } + + public boolean isCharacters() { + if (state == START_ELEMENT_STATE || state == END_ELEMENT_STATE) { + return false; + } + return childReader.isCharacters(); + } + + /** + * are we done ? + */ + public boolean isDone() { + return state == END_ELEMENT_STATE; + } + + public boolean isEndElement() { + if (state == START_ELEMENT_STATE) { + return false; + } else if (state == END_ELEMENT_STATE) { + return true; + } + return childReader.isEndElement(); + } + + public boolean isStandalone() { + return true; + } + + public boolean isStartElement() { + if (state == START_ELEMENT_STATE) { + return true; + } else if (state == END_ELEMENT_STATE) { + return false; + } + return childReader.isStartElement(); + } + + public boolean isWhiteSpace() { + if (state == START_ELEMENT_STATE || state == END_ELEMENT_STATE) { + return false; + } + return childReader.isWhiteSpace(); + } + + /** + * Get the prefix list from the hastable and take that into an array + */ + private String[] makePrefixArray() { + String[] prefixes = declaredNamespaceMap.keySet().toArray(new String[declaredNamespaceMap.size()]); + Arrays.sort(prefixes); + return prefixes; + } + + /** + * By far this should be the most important method in this class this method + * changes the state of the parser + */ + public int next() throws XMLStreamException { + int returnEvent = -1; // invalid state is the default state + switch (state) { + case START_ELEMENT_STATE: + // current element is start element. We should be looking at the + // property list and making a pullparser for the property value + if (getElements() == null || getElements().length == 0) { + // no properties - move to the end element state + // straightaway + state = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + } else { + // there are properties. now we should delegate this task to + // a + // child reader depending on the property type + returnEvent = processProperties(); + + } + break; + case END_ELEMENT_STATE: + // we've reached the end element already. If the user tries to + // push + // further ahead then it is an exception + throw new XMLStreamException("Trying to go beyond the end of the pullparser"); + + case DELEGATED_STATE: + if (childReader.isDone()) { + // we've reached the end! + if (index > (getElements().length - 1)) { + state = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + } else { + returnEvent = processProperties(); + } + } else { + returnEvent = childReader.next(); + } + break; + + case TEXT_STATE: + // if there are any more event we should be delegating to + // processProperties. if not we just return an end element + if (index > (getElements().length - 1)) { + state = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + } else { + returnEvent = processProperties(); + } + break; + } + return returnEvent; + } + + // ///////////////////////////////////////////////////////////////////////// + // / Other utility methods + // //////////////////////////////////////////////////////////////////////// + + /** + * todo implement this + * + * @throws XMLStreamException + */ + public int nextTag() throws XMLStreamException { + return 0; + } + + /** + * Populates a namespace context + */ + private void populateNamespaceContext() { + + // first add the current element namespace to the namespace context + // declare it if not found + addToNsMap(elementQName.getPrefix(), elementQName.getNamespaceURI()); + + for (QName n : getNamespaces()) { + addToNsMap(n.getPrefix(), n.getNamespaceURI()); + } + + // traverse through the attributes and populate the namespace context + // the attrib list can be of many combinations + // the valid combinations are + // String - String + // QName - QName + // null - OMAttribute + + for (int i = 0; i < getAttributes().length; i++) { // jump in two + QName attrQName = getAttributes()[i].getKey(); + if (!"".equals(attrQName.getNamespaceURI())) { + addToNsMap(attrQName.getPrefix(), attrQName.getNamespaceURI()); + } + } + } + + /** + * A convenient method to reuse the properties + * + * @return event to be thrown + * @throws XMLStreamException + */ + private int processProperties() throws XMLStreamException { + // move to the next property depending on the current property + // index + QName propertyQName = getElements()[index].getKey(); + boolean textFound = false; + if (propertyQName == null) { + throw new XMLStreamException("property key cannot be null!"); + } else if (ELEMENT_TEXT.equals(propertyQName.getLocalPart())) { + // propPointer being a String has a special case + // that is it can be a the special constant ELEMENT_TEXT that + // says this text event + textFound = true; + } + + // ok! we got the key. Now look at the value + Object propertyValue = getElements()[index].getValue(); + // cater for the special case now + if (textFound) { + // no delegation here - make the parser null and immediately + // return with the event characters + childReader = null; + state = TEXT_STATE; + ++index; + return CHARACTERS; + } else if (propertyValue == null) { + // if the value is null we delegate the work to a nullable + // parser + childReader = new NilElementStreamReader(propertyQName); + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else if (propertyValue instanceof String) { + // strings are handled by the NameValuePairStreamReader + childReader = new NameValuePairStreamReader(propertyQName, (String)propertyValue); + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else if (propertyValue instanceof String[]) { + // string[] are handled by the NameValueArrayStreamReader + // if the array is empty - skip it + if (((String[])propertyValue).length == 0) { + // advance the index + ++index; + return processProperties(); + } else { + childReader = new NameValueArrayStreamReader(propertyQName, (String[])propertyValue); + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } + + } else if (propertyValue instanceof XMLStreamable) { + // ADBbean has it's own method to get a reader + XMLStreamReader reader = ((XMLStreamable)propertyValue).getXMLStreamReader(propertyQName); + // we know for sure that this is an ADB XMLStreamreader. + // However we need to make sure that it is compatible + if (reader instanceof XMLFragmentStreamReader) { + childReader = (XMLFragmentStreamReader)reader; + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else { + // wrap it to make compatible + childReader = new WrappingXMLStreamReader(reader); + } + } else if (propertyValue instanceof XMLStreamReader) { + XMLStreamReader reader = (XMLStreamReader)propertyValue; + if (reader instanceof XMLFragmentStreamReader) { + childReader = (XMLFragmentStreamReader)reader; + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else { + // wrap it to make compatible + childReader = new WrappingXMLStreamReader(reader); + } + + } else { + // all special possiblilities has been tried! Let's treat + // the thing as a bean and try generating events from it + childReader = new WrappingXMLStreamReader(BeanUtil.getXMLStreamReader(propertyValue, propertyQName)); + // we cannot register the namespace context here + } + + // set the state here + state = DELEGATED_STATE; + // we are done with the delegation + // increment the property index + ++index; + return childReader.getEventType(); + } + + public void require(int i, String string, String string1) throws XMLStreamException { + throw new UnsupportedOperationException(); + } + + public boolean standaloneSet() { + return true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.java new file mode 100644 index 0000000000..08bfed9545 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.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.tuscany.sca.databinding.xml; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import java.lang.annotation.Annotation; + +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLEventWriter; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.Result; +import javax.xml.transform.Source; + +import org.apache.tuscany.sca.databinding.impl.GroupDataBinding; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; + +/** + * A Group DataBinding + * + * @version $Rev$ $Date$ + */ +public class XMLGroupDataBinding extends GroupDataBinding { + + public XMLGroupDataBinding() { + super(new Class[] {InputStream.class, OutputStream.class, Reader.class, Writer.class, Source.class, + Result.class, InputSource.class, ContentHandler.class, XMLStreamReader.class, + XMLStreamWriter.class, XMLEventReader.class, XMLEventWriter.class}); + } + + @Override + protected Object getLogical(Class<?> markerType, Annotation[] annotations) { + return XMLType.UNKNOWN; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.java new file mode 100644 index 0000000000..909e8ad57d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.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.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +/** + * Transform DOM Node to XML XMLStreamReader + */ +public class XMLStreamReader2Node extends BaseTransformer<XMLStreamReader, Node> implements + PullTransformer<XMLStreamReader, Node> { + + private XMLStreamReader2SAX stax2sax = new XMLStreamReader2SAX(); + + public Node transform(XMLStreamReader source, TransformationContext context) { + try { + DataPipe<ContentHandler, Node> pipe = new SAX2DOMPipe().newInstance(); + stax2sax.transform(source, pipe.getSink(), context); + Node node = pipe.getResult(); + source.close(); + return node; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.java new file mode 100644 index 0000000000..8d12b2574e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.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.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.xml.sax.ContentHandler; + +/** + * XMLStreamReader to SAX events + */ +public class XMLStreamReader2SAX extends BaseTransformer<XMLStreamReader, ContentHandler> implements + PushTransformer<XMLStreamReader, ContentHandler> { + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#getSourceType() + */ + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#getSourceType() + */ + @Override + public Class getSourceType() { + return XMLStreamReader.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#getWeight() + */ + @Override + public int getWeight() { + return 20; + } + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#transform(java.lang.Object, + * java.lang.Object, + * org.apache.tuscany.sca.databinding.TransformationContext) + */ + public void transform(XMLStreamReader source, ContentHandler sink, TransformationContext context) { + StAX2SAXAdapter adapter = new StAX2SAXAdapter(false); + try { + adapter.parse(source, sink); + source.close(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.java new file mode 100755 index 0000000000..fd1cab54b3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +public class XMLStreamReader2String extends BaseTransformer<XMLStreamReader, String> implements + PullTransformer<XMLStreamReader, String> { + + public String transform(XMLStreamReader source, TransformationContext context) { + try { + String str = StAXHelper.save(source); + source.close(); + return str; + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + public Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamSerializer.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamSerializer.java new file mode 100644 index 0000000000..93939c5cd7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamSerializer.java @@ -0,0 +1,285 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +/** + * The XMLStreamSerializer pulls events from the XMLStreamReader and dumps into the XMLStreamWriter + */ +public class XMLStreamSerializer implements XMLStreamConstants { + public static final String NAMESPACE_PREFIX = "ns"; + private static int namespaceSuffix; + + /* + * The behavior of the serializer is such that it returns when it encounters the starting element for the second + * time. The depth variable tracks the depth of the serilizer and tells it when to return. Note that it is assumed + * that this serialization starts on an Element. + */ + + /** + * Field depth + */ + private int depth; + + /** + * Generates a unique namespace prefix that is not in the scope of the NamespaceContext + * + * @param nsCtxt + * @return string + */ + private String generateUniquePrefix(NamespaceContext nsCtxt) { + String prefix = NAMESPACE_PREFIX + namespaceSuffix++; + // null should be returned if the prefix is not bound! + while (nsCtxt.getNamespaceURI(prefix) != null) { + prefix = NAMESPACE_PREFIX + namespaceSuffix++; + } + + return prefix; + } + + /** + * Method serialize. + * + * @param node + * @param writer + * @throws XMLStreamException + */ + public void serialize(XMLStreamReader node, XMLStreamWriter writer) throws XMLStreamException { + serializeNode(node, writer); + } + + /** + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeAttributes(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + int count = reader.getAttributeCount(); + String prefix; + String namespaceName; + String writerPrefix; + for (int i = 0; i < count; i++) { + prefix = reader.getAttributePrefix(i); + namespaceName = reader.getAttributeNamespace(i); + /* + * Due to parser implementations returning null as the namespace URI (for the empty namespace) we need to + * make sure that we deal with a namespace name that is not null. The best way to work around this issue is + * to set the namespace uri to "" if it is null + */ + if (namespaceName == null) { + namespaceName = ""; + } + + writerPrefix = writer.getNamespaceContext().getPrefix(namespaceName); + + if (!"".equals(namespaceName)) { + // prefix has already being declared but this particular + // attrib has a + // no prefix attached. So use the prefix provided by the + // writer + if (writerPrefix != null && (prefix == null || prefix.equals(""))) { + writer.writeAttribute(writerPrefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + + // writer prefix is available but different from the + // current + // prefix of the attrib. We should be decalring the new + // prefix + // as a namespace declaration + } else if (prefix != null && !"".equals(prefix) && !prefix.equals(writerPrefix)) { + writer.writeNamespace(prefix, namespaceName); + writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + + // prefix is null (or empty), but the namespace name is + // valid! it has not + // being written previously also. So we need to generate + // a prefix + // here + } else if (prefix == null || prefix.equals("")) { + prefix = generateUniquePrefix(writer.getNamespaceContext()); + writer.writeNamespace(prefix, namespaceName); + writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + } else { + writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + } + } else { + // empty namespace is equal to no namespace! + writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); + } + + } + } + + /** + * Method serializeCData. + * + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeCData(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + writer.writeCData(reader.getText()); + } + + /** + * Method serializeComment. + * + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeComment(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + writer.writeComment(reader.getText()); + } + + /** + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeElement(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + String prefix = reader.getPrefix(); + String nameSpaceName = reader.getNamespaceURI(); + if (nameSpaceName != null) { + String writerPrefix = writer.getPrefix(nameSpaceName); + if (writerPrefix != null) { + writer.writeStartElement(nameSpaceName, reader.getLocalName()); + } else { + if (prefix != null) { + writer.writeStartElement(prefix, reader.getLocalName(), nameSpaceName); + writer.writeNamespace(prefix, nameSpaceName); + writer.setPrefix(prefix, nameSpaceName); + } else { + // [rfeng] We need to set default NS 1st before calling writeStateElement + writer.setDefaultNamespace(nameSpaceName); + writer.writeStartElement(nameSpaceName, reader.getLocalName()); + writer.writeDefaultNamespace(nameSpaceName); + } + } + } else { + writer.writeStartElement(reader.getLocalName()); + } + + // add the namespaces + int count = reader.getNamespaceCount(); + String namespacePrefix; + for (int i = 0; i < count; i++) { + namespacePrefix = reader.getNamespacePrefix(i); + // [rfeng] The following is commented out to allow to default ns + // if (namespacePrefix != null && namespacePrefix.length() == 0) { + // continue; + // } + + serializeNamespace(namespacePrefix, reader.getNamespaceURI(i), writer); + } + + // add attributes + serializeAttributes(reader, writer); + + } + + /** + * Method serializeEndElement. + * + * @param writer + * @throws XMLStreamException + */ + protected void serializeEndElement(XMLStreamWriter writer) throws XMLStreamException { + writer.writeEndElement(); + } + + /** + * Method serializeNamespace. + * + * @param prefix + * @param uri + * @param writer + * @throws XMLStreamException + */ + private void serializeNamespace(String prefix, String uri, XMLStreamWriter writer) throws XMLStreamException { + String prefix1 = writer.getPrefix(uri); + if (prefix1 == null) { + writer.writeNamespace(prefix, uri); + writer.setPrefix(prefix, uri); + } + } + + /** + * Method serializeNode. + * + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeNode(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + while (true) { + int event = reader.getEventType(); + if (event == START_ELEMENT) { + serializeElement(reader, writer); + depth++; + } else if (event == ATTRIBUTE) { + serializeAttributes(reader, writer); + } else if (event == CHARACTERS) { + serializeText(reader, writer); + } else if (event == COMMENT) { + serializeComment(reader, writer); + } else if (event == CDATA) { + serializeCData(reader, writer); + } else if (event == END_ELEMENT) { + serializeEndElement(writer); + depth--; + } else if (event == START_DOCUMENT) { + depth++; // if a start document is found then increment + writer.writeStartDocument(); + // the depth + } else if (event == END_DOCUMENT) { + if (depth != 0) { + depth--; // for the end document - reduce the depth + } + writer.writeEndDocument(); + } + if (depth == 0) { + break; + } + if (reader.hasNext()) { + reader.next(); + } else { + break; + } + } + } + + /** + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeText(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + writer.writeCharacters(reader.getText()); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamable.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamable.java new file mode 100644 index 0000000000..f32f93d098 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamable.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.tuscany.sca.databinding.xml; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +/** + * An interface represents data that can be read using StAX streaming + * + * @version $Rev$ $Date$ + */ +public interface XMLStreamable { + /** + * Get the XMLStreamReader for StAX processing + * + * @param rootElementName the name of the element to be generated + * @return Returns a pull parser. + */ + XMLStreamReader getXMLStreamReader(QName rootElementName); +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.java new file mode 100644 index 0000000000..21307909a7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.xml; + +import java.lang.annotation.Annotation; + +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * A DataBinding for the XML string + * + * @version $Rev$ $Date$ + */ +public class XMLStringDataBinding extends BaseDataBinding { + public static final String NAME = String.class.getName(); + public static final String[] ALIASES = new String[] {"xml.string"}; + + public XMLStringDataBinding() { + super(NAME, ALIASES, String.class); + } + + @Override + public boolean introspect(DataType type, Annotation[] annotations) { + if (type.getPhysical() == String.class && NAME.equals(type.getDataBinding()) || ALIASES[0].equals(type.getDataBinding())) { + type.setDataBinding(NAME); + type.setLogical(XMLType.UNKNOWN); + return true; + } else { + return false; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..ad7e79c18b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -0,0 +1,23 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# implementation classes for the databindings +org.apache.tuscany.sca.databinding.xml.DOMDataBinding;type=org.w3c.dom.Node,name=dom +org.apache.tuscany.sca.databinding.xml.XMLStringDataBinding;type=java.lang.String,name=xml.string +org.apache.tuscany.sca.databinding.xml.XMLGroupDataBinding;type=databinding:group +org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding;type=java.lang.Object +org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding;type=java:simpleType diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint new file mode 100644 index 0000000000..568e04f9de --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.databinding.DefaultDataBindingExtensionPoint diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..9012c210cb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.xml.InputSource2Node;source=org.xml.sax.InputSource,target=org.w3c.dom.Node,weight=40 +org.apache.tuscany.sca.databinding.xml.InputStream2Node;source=java.io.InputStream,target=org.w3c.dom.Node,weight=40 +org.apache.tuscany.sca.databinding.javabeans.DOMNode2JavaBeanTransformer;source=org.w3c.dom.Node,target=java.lang.Object,weight=10000 +org.apache.tuscany.sca.databinding.xml.Node2String;source=org.w3c.dom.Node,target=java.lang.String,weight=40 +org.apache.tuscany.sca.databinding.xml.Node2XMLStreamReader;source=org.w3c.dom.Node,target=javax.xml.stream.XMLStreamReader,weight=40 +org.apache.tuscany.sca.databinding.javabeans.JavaBean2DOMNodeTransformer;source=java.lang.Object,target=org.w3c.dom.Node,weight=10000 +org.apache.tuscany.sca.databinding.xml.Reader2Node;source=java.io.Reader,target=org.w3c.dom.Node,weight=40 +org.apache.tuscany.sca.databinding.xml.SAX2DOMPipe;source=org.xml.sax.ContentHandler,target=org.w3c.dom.Node,weight=30 +org.apache.tuscany.sca.databinding.xml.StreamDataPipe;source=java.io.OutputStream,target=java.io.InputStream,weight=50 +org.apache.tuscany.sca.databinding.xml.String2Node;source=java.lang.String,target=org.w3c.dom.Node,weight=50 +org.apache.tuscany.sca.databinding.xml.String2XMLStreamReader;source=java.lang.String,target=javax.xml.stream.XMLStreamReader,weight=50 +org.apache.tuscany.sca.databinding.xml.Writer2ReaderDataPipe;source=java.io.Writer,target=java.io.Reader,weight=50 +org.apache.tuscany.sca.databinding.xml.XMLStreamReader2Node;source=javax.xml.stream.XMLStreamReader,target=org.w3c.dom.Node,weight=40 +org.apache.tuscany.sca.databinding.xml.XMLStreamReader2String;source=javax.xml.stream.XMLStreamReader,target=java.lang.String,weight=40 +org.apache.tuscany.sca.databinding.xml.Node2SimpleJavaType;source=org.w3c.dom.Node,target=java:simpleType,weight=10000 +org.apache.tuscany.sca.databinding.xml.SimpleJavaType2Node;source=java:simpleType,target=org.w3c.dom.Node,weight=10000 diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer new file mode 100644 index 0000000000..6ba1ea32a9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer @@ -0,0 +1,26 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.xml.InputSource2SAX;source=org.xml.sax.InputSource,target=org.xml.sax.ContentHandler,weight=40 +org.apache.tuscany.sca.databinding.xml.InputStream2SAX;source=java.io.InputStream,target=org.xml.sax.ContentHandler,weight=40 +org.apache.tuscany.sca.databinding.xml.Node2OutputStream;source=org.w3c.dom.Node,target=java.io.OutputStream,weight=40 +org.apache.tuscany.sca.databinding.xml.Node2Writer;source=org.w3c.dom.Node,target=java.io.Writer,weight=40 +org.apache.tuscany.sca.databinding.xml.Reader2SAX;source=java.io.Reader,target=org.xml.sax.ContentHandler,weight=40 +org.apache.tuscany.sca.databinding.xml.Source2ResultTransformer;source=javax.xml.transform.Source,target=javax.xml.transform.Result,weight=40 +org.apache.tuscany.sca.databinding.xml.String2SAX;source=java.lang.String,target=org.xml.sax.ContentHandler,weight=40 +org.apache.tuscany.sca.databinding.xml.XMLStreamReader2SAX;source=javax.xml.stream.XMLStreamReader,target=org.xml.sax.ContentHandler,weight=20 diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint new file mode 100644 index 0000000000..7d8642fb1e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.databinding.DefaultTransformerExtensionPoint diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DOMHelperTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DOMHelperTestCase.java new file mode 100644 index 0000000000..d210ad1371 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DOMHelperTestCase.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.extension; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * + */ +public class DOMHelperTestCase extends TestCase { + private static final QName FOO_NAME = new QName("http://foo", "foo"); + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testDOM() throws Exception { + DocumentBuilder builder = DOMHelper.newDocumentBuilder(); + assertNotNull(builder); + Document document = DOMHelper.newDocument(); + assertNotNull(document); + Element element = DOMHelper.createElement(document, FOO_NAME); + document.appendChild(element); + QName name = DOMHelper.getQName(element); + assertEquals(FOO_NAME, name); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.java new file mode 100644 index 0000000000..174202842a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.extension; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.easymock.EasyMock; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * + */ +public class DataBindingExtensionTestCase extends TestCase { + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + @SuppressWarnings("unchecked") + public void testExtension() { + DataBinding1 binding1 = new DataBinding1(Node.class); + assertEquals(Node.class.getName(), binding1.getName()); + DataType dt1 = new DataTypeImpl<Class>(Element.class, null); + assertTrue(binding1.introspect(dt1, null)); + DataType dt2 = new DataTypeImpl<Class>(String.class, null); + assertFalse(binding1.introspect(dt2, null)); + assertNull(binding1.getWrapperHandler()); + + DataBindingExtensionPoint registry = EasyMock.createMock(DataBindingExtensionPoint.class); + registry.addDataBinding(binding1); + EasyMock.expect(registry.getDataBinding(Node.class.getName())).andReturn(binding1); + EasyMock.replay(registry); + + assertNotNull(registry.getDataBinding(Node.class.getName())); + + DataBinding1 binding2 = new DataBinding1("dom", Node.class); + assertEquals("dom", binding2.getName()); + } + + private static class DataBinding1 extends BaseDataBinding { + + /** + * @param baseType + */ + public DataBinding1(Class<?> baseType) { + super(baseType); + } + + /** + * @param name + * @param baseType + */ + public DataBinding1(String name, Class<?> baseType) { + super(name, baseType); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.java new file mode 100644 index 0000000000..4e321f2055 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.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.tuscany.sca.databinding.extension; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.easymock.EasyMock; + +/** + * + */ +public class SimpleTypeMapperExtensionTestCase extends TestCase { + + private static final Map<String, Object> SAMPLE_VALUES = new HashMap<String, Object>(); + + static { + SAMPLE_VALUES.put("anyURI", "http://www.w3.com"); + SAMPLE_VALUES.put("boolean", new String[] {"true", "false", "1", "0"}); + SAMPLE_VALUES.put("byte", new String[] {"-128", "127"}); + SAMPLE_VALUES.put("date", new String[] {"2004-03-15", "2002-09-24-06:00"}); + SAMPLE_VALUES.put("dateTime", "2003-12-25T08:30:00"); + SAMPLE_VALUES.put("decimal", "3.1415292"); + SAMPLE_VALUES.put("double", new String[] {"3.1415292", "INF", "NaN"}); + SAMPLE_VALUES.put("duration", new String[] {"P8M3DT7H33M2S", "P5Y2M10DT15H"}); + SAMPLE_VALUES.put("float", new String[] {"3.1415292", "INF", "NaN"}); + SAMPLE_VALUES.put("gDay", "---11"); + if (System.getProperty("java.vendor").toUpperCase().contains("SUN") && System.getProperty("java.version") + .contains("1.5.0")) { + // Work around a bug in SUN JDK + SAMPLE_VALUES.put("gMonth", "--02--"); + } else { + SAMPLE_VALUES.put("gMonth", "--02"); + } + SAMPLE_VALUES.put("gMonthDay", "--02-14"); + SAMPLE_VALUES.put("gYear", "1999"); + SAMPLE_VALUES.put("gYearMonth", "1972-08"); + SAMPLE_VALUES.put("ID", "id-102"); + SAMPLE_VALUES.put("IDREF", "id-102"); + SAMPLE_VALUES.put("IDREFS", "id-102 id-103 id-100"); + SAMPLE_VALUES.put("int", "77"); + SAMPLE_VALUES.put("integer", "77"); + SAMPLE_VALUES.put("long", "214"); + SAMPLE_VALUES.put("negativeInteger", "-123"); + SAMPLE_VALUES.put("nonNegativeInteger", "2"); + SAMPLE_VALUES.put("nonPositiveInteger", "0"); + SAMPLE_VALUES.put("positiveInteger", "500"); + SAMPLE_VALUES.put("short", "476"); + SAMPLE_VALUES.put("string", "Joeseph"); + SAMPLE_VALUES.put("time", "13:02:00"); + SAMPLE_VALUES.put("base64Binary", "TWFu"); + SAMPLE_VALUES.put("hexBinary", "2CDB5F"); + SAMPLE_VALUES.put("QName", "f:foo"); + SAMPLE_VALUES.put("NOTATION", "f:bar"); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testMap() throws Exception { + SimpleTypeMapperImpl extension = new SimpleTypeMapperImpl(); + TransformationContext context = EasyMock.createMock(TransformationContext.class); + Map<String, Object> metaData = new HashMap<String, Object>(); + EasyMock.expect(context.getMetadata()).andReturn(metaData).anyTimes(); + EasyMock.replay(context); + + NamespaceContext namespaceContext = EasyMock.createMock(NamespaceContext.class); + EasyMock.expect(namespaceContext.getNamespaceURI(EasyMock.eq("f"))).andReturn("http://foo").anyTimes(); + EasyMock.expect(namespaceContext.getPrefix(EasyMock.eq("http://foo"))).andReturn("f").anyTimes(); + EasyMock.replay(namespaceContext); + context.getMetadata().put(NamespaceContext.class.getName(), namespaceContext); + for (TypeInfo simpleType : SimpleTypeMapperImpl.XSD_SIMPLE_TYPES.values()) { + String name = simpleType.getQName().getLocalPart(); + Object value = SAMPLE_VALUES.get(name); + if (value instanceof String[]) { + for (String s : (String[])value) { + Object obj = extension.toJavaObject(simpleType.getQName(), s, context); + String str = extension.toXMLLiteral(simpleType.getQName(), obj, context); + assertNotNull(str); + // assertTrue("[" + name + "] " + s + " " + str, + // str.contains((String) s)); + } + } else if (value instanceof String) { + Object obj = extension.toJavaObject(simpleType.getQName(), (String)value, context); + String str = extension.toXMLLiteral(simpleType.getQName(), obj, context); + assertNotNull(str); + // assertTrue("[" + name + "] " + value + " " + str, + // str.contains((String) value)); + } + } + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.java new file mode 100644 index 0000000000..08141583c3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.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.tuscany.sca.databinding.extension; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.easymock.EasyMock; +import org.w3c.dom.Node; + +/** + * Test case for TransformerExtension + */ +public class TransformerExtensionTestCase extends TestCase { + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testExtension() { + MyTransformer transformer = new MyTransformer(); + assertEquals(Node.class.getName(), transformer.getSourceDataBinding()); + assertEquals(XMLStreamReader.class.getName(), transformer.getTargetDataBinding()); + assertEquals(50, transformer.getWeight()); + TransformerExtensionPoint registry = EasyMock.createMock(TransformerExtensionPoint.class); + registry.addTransformer(EasyMock.isA(Transformer.class)); + EasyMock + .expect(registry.getTransformer(transformer.getSourceDataBinding(), transformer.getTargetDataBinding())) + .andReturn(transformer); + EasyMock.replay(registry); + registry.addTransformer(transformer); + assertSame(transformer, registry.getTransformer(transformer.getSourceDataBinding(), transformer + .getTargetDataBinding())); + } + + private static class MyTransformer extends BaseTransformer<Node, XMLStreamReader> { + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.java new file mode 100644 index 0000000000..31eed42c06 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.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.tuscany.sca.databinding.extension; + +import java.math.BigInteger; +import java.util.Calendar; +import java.util.GregorianCalendar; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.impl.XSDDataTypeConverter; + +/** + * + */ +public class XSDDataTypeConverterTestCase extends TestCase { + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testConvert() throws Exception { + XSDDataTypeConverter c = new XSDDataTypeConverter(); + assertEquals("123", c.parseAnySimpleType(c.printAnySimpleType("123"))); + assertEquals(true, c.parseBoolean(c.printBoolean(true))); + assertEquals(false, c.parseBoolean(c.printBoolean(false))); + assertEquals(123.0, c.parseDouble(c.printDouble(123.0))); + assertEquals(123.0f, c.parseFloat(c.printFloat(123.0f))); + assertEquals(64, c.parseByte(c.printByte((byte)64))); + assertEquals(123, c.parseInt(c.printInt(123))); + assertEquals(new BigInteger("123456"), c.parseInteger(c.printInteger(new BigInteger("123456")))); + assertEquals(123456L, c.parseLong(c.printLong(123456L))); + assertEquals((short)123, c.parseShort(c.printShort((short)123))); + + Calendar calendar = new GregorianCalendar(); + String s = c.printDate(calendar); + calendar = c.parseDate(s); + assertEquals(s, c.printDate(calendar)); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingRegistryImplTestCase.java new file mode 100644 index 0000000000..1aa90cce1b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingRegistryImplTestCase.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.tuscany.sca.databinding.impl; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.lang.annotation.Annotation; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultDataBindingExtensionPoint; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.easymock.EasyMock; +import org.xml.sax.ContentHandler; + +/** + * + */ +public class DataBindingRegistryImplTestCase extends TestCase { + private DataBindingExtensionPoint registry; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + registry = new DefaultDataBindingExtensionPoint(); + } + + @SuppressWarnings("unchecked") + public void testRegistry() { + DataBinding db1 = createMock(DataBinding.class); + expect(db1.getAliases()).andReturn(new String[] {"db1"}).anyTimes(); + expect(db1.getName()).andReturn(ContentHandler.class.getName()).anyTimes(); + DataType<Class> dataType1 = new DataTypeImpl<Class>(ContentHandler.class, ContentHandler.class); + expect(db1.introspect(dataType1, null)).andReturn(true); + expect(db1.introspect(EasyMock.not(EasyMock.same(dataType1)), (Annotation[])EasyMock.isNull())) + .andReturn(false).anyTimes(); + replay(db1); + + registry.addDataBinding(db1); + + DataBinding db2 = createMock(DataBinding.class); + expect(db2.getAliases()).andReturn(new String[] {"db2"}).anyTimes(); + expect(db2.getName()).andReturn(XMLStreamReader.class.getName()).anyTimes(); + DataType<Class> dataType2 = new DataTypeImpl<Class>(XMLStreamReader.class, XMLStreamReader.class); + expect(db2.introspect(dataType2, null)).andReturn(true); + expect(db2.introspect(EasyMock.not(EasyMock.same(dataType2)), (Annotation[])EasyMock.isNull())) + .andReturn(false).anyTimes(); + replay(db2); + + registry.addDataBinding(db2); + + // Lookup by name + String name = db1.getName(); + DataBinding db3 = registry.getDataBinding(name); + assertSame(db1, db3); + + // Look up by alias + DataBinding db5 = registry.getDataBinding("db1"); + assertSame(db1, db5); + + DataType dt = new DataTypeImpl<Class>(ContentHandler.class, null); + registry.introspectType(dt, null); + assertEquals(dataType1.getLogical(), ContentHandler.class); + //FIXME does not match with dynamically loaded databindings + //assertTrue(dt.getDataBinding().equalsIgnoreCase("java.lang.Object")); + + registry.removeDataBinding(name); + DataBinding db4 = registry.getDataBinding(name); + assertNull(db4); + + dt = new DataTypeImpl<Class>(null, String.class, null); + registry.introspectType(dt, null); + //FIXME does not match with dynamically loaded databindings + //assertEquals("java.lang.Object", dt.getDataBinding()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.java new file mode 100644 index 0000000000..1dc91374ea --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.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.tuscany.sca.databinding.impl; + +import java.lang.reflect.Method; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.annotation.DataBinding; + +public class DataBindingTestCase extends TestCase { + @SuppressWarnings("unused") + public void testDataType() throws Exception { + Class<Test> testClass = Test.class; + DataBinding d = testClass.getAnnotation(DataBinding.class); + Assert.assertEquals(d.value(), "sdo"); + + Method method = testClass.getMethod("test", new Class[] {Object.class}); + DataBinding d2 = method.getAnnotation(DataBinding.class); + Assert.assertEquals(d2.value(), "jaxb"); + } + + @DataBinding("sdo") + private static interface Test { + @DataBinding("jaxb") + Object test(Object object); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.java new file mode 100755 index 0000000000..3025dbfd13 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.impl.DirectedGraph.Edge; +import org.apache.tuscany.sca.databinding.impl.DirectedGraph.Vertex; + +public class DirectedGraphTestCase extends TestCase { + private DirectedGraph<String, Object> graph; + + @Override + protected void setUp() throws Exception { + super.setUp(); + graph = new DirectedGraph<String, Object>(); + graph.addEdge("a", "b", null, 3); + graph.addEdge("b", "c", null, 1); + graph.addEdge("a", "c", null, 8); + graph.addEdge("a", "d", null, 3); + graph.addEdge("b", "d", null, 2); + graph.addEdge("c", "b", null, 1); + graph.addEdge("c", "d", null, 2); + graph.addEdge("d", "b", null, 1); + graph.addEdge("a", "e", null, 8); + graph.addEdge("c", "c", null, 2); + } + + public void testGraph() { + // System.out.println(graph); + + Vertex vertex = graph.getVertex("a"); + Assert.assertNotNull(vertex); + Assert.assertEquals(vertex.getValue(), "a"); + + Assert.assertNull(graph.getVertex("1")); + + Edge edge = graph.getEdge("a", "b"); + Assert.assertNotNull(edge); + Assert.assertEquals(edge.getWeight(), 3); + + edge = graph.getEdge("b", "a"); + Assert.assertNull(edge); + + DirectedGraph<String, Object>.Path path = graph.getShortestPath("a", "c"); + + List<DirectedGraph<String, Object>.Edge> edges = path.getEdges(); + Assert.assertEquals(edges.size(), 2); + Assert.assertEquals(edges.get(0), graph.getEdge("a", "b")); + Assert.assertEquals(edges.get(1), graph.getEdge("b", "c")); + + Assert.assertEquals(path.getWeight(), 4); + + DirectedGraph<String, Object>.Path path2 = graph.getShortestPath("b", "e"); + Assert.assertNull(path2); + + DirectedGraph<String, Object>.Path path3 = graph.getShortestPath("a", "a"); + Assert.assertTrue(path3.getWeight() == 0 && path3.getEdges().isEmpty()); + + DirectedGraph<String, Object>.Path path4 = graph.getShortestPath("c", "c"); + Assert.assertTrue(path4.getWeight() == 2 && path4.getEdges().size() == 1); + + // System.out.println(path); + + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.java new file mode 100644 index 0000000000..391fcde38c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.impl; + +import java.io.StringWriter; +import java.io.Writer; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultDataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultTransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.xml.Node2String; +import org.apache.tuscany.sca.databinding.xml.Node2Writer; +import org.apache.tuscany.sca.databinding.xml.SAX2DOMPipe; +import org.apache.tuscany.sca.databinding.xml.String2SAX; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Test case for MediatorImpl + */ +public class MediatorImplTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + "<state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + "<USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + private MediatorImpl mediator; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + DataBindingExtensionPoint dataBindingRegistry = new DefaultDataBindingExtensionPoint(); + TransformerExtensionPoint registry = new DefaultTransformerExtensionPoint(); + + registry.addTransformer(new String2SAX()); + registry.addTransformer(new SAX2DOMPipe()); + registry.addTransformer(new Node2String()); + registry.addTransformer(new Node2Writer()); + + mediator = new MediatorImpl(dataBindingRegistry, registry); + } + + private TransformationContext createTransformationContext(Class sourceType, Class targetType) { + TransformationContext context = new TransformationContextImpl(); + DataType sourceDataType = new DataTypeImpl<Class>(sourceType.getName(), sourceType, sourceType); + DataType targetDataType = new DataTypeImpl<Class>(targetType.getName(), targetType, targetType); + context.setSourceDataType(sourceDataType); + context.setTargetDataType(targetDataType); + return context; + } + + public void testTransform1() { + TransformationContext context = createTransformationContext(String.class, Node.class); + Object node = + mediator.mediate(IPO_XML, context.getSourceDataType(), context.getTargetDataType(), null); + Assert.assertTrue(node instanceof Document); + Element root = ((Document)node).getDocumentElement(); + Assert.assertEquals(root.getNamespaceURI(), "http://www.example.com/IPO"); + Assert.assertEquals(root.getLocalName(), "purchaseOrder"); + } + + public void testTransform2() { + TransformationContext context = createTransformationContext(String.class, Writer.class); + Writer writer = new StringWriter(); + mediator.mediate(IPO_XML, writer, context.getSourceDataType(), context.getTargetDataType(), null); + String str = writer.toString(); + Assert.assertTrue(str != null && str.indexOf("<shipDate>1999-12-05</shipDate>") != -1); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/TransformerRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/TransformerRegistryImplTestCase.java new file mode 100644 index 0000000000..f6b31b63a8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/TransformerRegistryImplTestCase.java @@ -0,0 +1,108 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.impl; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.DefaultTransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; + +/** + * + */ +public class TransformerRegistryImplTestCase extends TestCase { + private TransformerExtensionPoint registry; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + registry = new DefaultTransformerExtensionPoint(); + } + + public void testRegisterTransformer1() { + Transformer transformer = createMock(Transformer.class); + registry.addTransformer("a", "b", 10, transformer); + Transformer t = registry.getTransformer("a", "b"); + Assert.assertSame(t, transformer); + } + + public void testRegisterTransformerTransformer() { + Transformer transformer = createMock(Transformer.class); + expect(transformer.getSourceDataBinding()).andReturn("a"); + expect(transformer.getTargetDataBinding()).andReturn("b"); + expect(transformer.getWeight()).andReturn(10); + replay(transformer); + registry.addTransformer(transformer); + Transformer t = registry.getTransformer("a", "b"); + Assert.assertSame(t, transformer); + } + + public void testUnregisterTransformer() { + Transformer transformer = createMock(Transformer.class); + registry.addTransformer("a", "b", 10, transformer); + boolean result = registry.removeTransformer("a", "b"); + Assert.assertTrue(result); + Transformer t = registry.getTransformer("a", "b"); + Assert.assertNull(t); + } + + public void testGetTransformerChain() { + Transformer t1 = createMock(Transformer.class); + expect(t1.getSourceDataBinding()).andReturn("a"); + expect(t1.getTargetDataBinding()).andReturn("b"); + expect(t1.getWeight()).andReturn(10); + replay(t1); + Transformer t2 = createMock(Transformer.class); + expect(t2.getSourceDataBinding()).andReturn("b"); + expect(t2.getTargetDataBinding()).andReturn("c"); + expect(t2.getWeight()).andReturn(20); + replay(t2); + + Transformer t3 = createMock(Transformer.class); + expect(t3.getSourceDataBinding()).andReturn("a"); + expect(t3.getTargetDataBinding()).andReturn("c"); + expect(t3.getWeight()).andReturn(120); + replay(t3); + + registry.addTransformer(t1); + registry.addTransformer(t2); + registry.addTransformer(t3); + + List<Transformer> l1 = registry.getTransformerChain("a", "b"); + Assert.assertTrue(l1.size() == 1 && l1.get(0) == t1); + List<Transformer> l2 = registry.getTransformerChain("a", "c"); + Assert.assertTrue(l2.size() == 2 && l2.get(0) == t1 && l2.get(1) == t2); + List<Transformer> l3 = registry.getTransformerChain("a", "d"); + Assert.assertNull(l3); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.java new file mode 100644 index 0000000000..5200cdacd5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.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.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.w3c.dom.Node; + +public class DOM2StAXTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + private static final String CRAZY_XML = + "<p:e1 xmlns=\"http://ns0\" xmlns:p=\"http://p1\">" + + "<p:e2 xmlns:p=\"http://p2\"/><e3/><e4 xmlns=\"\">E4</e4></p:e1>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransformation() { + String2Node t1 = new String2Node(); + Node node = t1.transform(IPO_XML, null); + Node2XMLStreamReader t2 = new Node2XMLStreamReader(); + XMLStreamReader reader = t2.transform(node, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(); + String xml = t3.transform(reader, null); + assertTrue(xml != null && xml.indexOf("<shipDate>1999-12-05</shipDate>") != -1); + } + + public void testTransformation2() { + String2Node t1 = new String2Node(); + Node node = t1.transform(CRAZY_XML, null); + Node2XMLStreamReader t2 = new Node2XMLStreamReader(); + XMLStreamReader reader = t2.transform(node, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(); + String xml = t3.transform(reader, null); + System.out.println(xml); + assertTrue(xml.contains("<p:e2 xmlns:p=\"http://p2\"")); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.java new file mode 100644 index 0000000000..b7184cef9c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.apache.tuscany.sca.databinding.impl.PipedTransformer; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Test case for DataPipe + */ +public class DataPipeTestCase extends TestCase { + + public final void testStreamPipe() throws IOException { + byte[] bytes = new byte[] {1, 2, 3}; + DataPipeTransformer<OutputStream, InputStream> pipe = new StreamDataPipe(); + DataPipe<OutputStream, InputStream> dataPipe = pipe.newInstance(); + OutputStream os = dataPipe.getSink(); + os.write(bytes); + byte[] newBytes = new byte[16]; + int count = dataPipe.getResult().read(newBytes); + Assert.assertEquals(3, count); + for (int i = 0; i < bytes.length; i++) { + Assert.assertEquals(bytes[i], newBytes[i]); + } + } + + public final void testWriter2ReaderPipe() throws IOException { + String str = "ABC"; + Writer2ReaderDataPipe pipe = new Writer2ReaderDataPipe(); + Assert.assertSame(Writer.class, pipe.getSourceType()); + Assert.assertSame(Reader.class, pipe.getTargetType()); + DataPipe<Writer, Reader> dataPipe = pipe.newInstance(); + dataPipe.getSink().write(str); + char[] buf = new char[16]; + int count = dataPipe.getResult().read(buf); + Assert.assertEquals(3, count); + for (int i = 0; i < str.length(); i++) { + Assert.assertEquals(str.charAt(i), buf[i]); + } + } + + public final void testPiped() throws Exception { + Node2Writer node2Writer = new Node2Writer(); + Writer2ReaderDataPipe pipe = new Writer2ReaderDataPipe(); + PipedTransformer<Node, Writer, Reader> transformer = + new PipedTransformer<Node, Writer, Reader>(node2Writer, pipe); + Document document = DOMHelper.newDocument(); + Element element = document.createElementNS("http://ns1", "root"); + document.appendChild(element); + Reader reader = transformer.transform(document, null); + Assert.assertEquals(transformer.getWeight(), node2Writer.getWeight() + pipe.getWeight()); + Assert.assertEquals(transformer.getSourceDataBinding(), node2Writer.getSourceDataBinding()); + Assert.assertEquals(transformer.getTargetDataBinding(), pipe.getTargetDataBinding()); + char[] buf = new char[120]; + int count = reader.read(buf); + String xml = new String(buf, 0, count); + Assert.assertTrue(xml.contains("<root xmlns=\"http://ns1\"/>")); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.java new file mode 100644 index 0000000000..3db8dad8a7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.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.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.javabeans.JavaBean2XMLStreamReader; + +public class JavaBean2XMLStreamReaderTestCase extends TestCase { + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransformation() { + JavaBean2XMLStreamReader t2 = new JavaBean2XMLStreamReader(); + MyBean bean = new MyBean(); + bean.str = "ABC"; + bean.i = 1; + bean.arr = new long[] {1, 2, 3}; + bean.bean = new AnotherBean(); + bean.bean.setName("Name"); + XMLStreamReader reader = t2.transform(bean, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(); + String xml = t3.transform(reader, null); + assertTrue(xml.contains("<JavaBean2XMLStreamReaderTestCase$MyBean>" + + "<arr>1</arr><arr>2</arr><arr>3</arr><bean><name>Name</name></bean>" + + "<i>1</i><str>ABC</str></JavaBean2XMLStreamReaderTestCase$MyBean>")); + } + + private static class MyBean { + private String str; + private int i; + private long arr[]; + private AnotherBean bean; + + /** + * @return the arr + */ + public long[] getArr() { + return arr; + } + + /** + * @param arr the arr to set + */ + public void setArr(long[] arr) { + this.arr = arr; + } + + /** + * @return the i + */ + public int getI() { + return i; + } + + /** + * @param i the i to set + */ + public void setI(int i) { + this.i = i; + } + + /** + * @return the str + */ + public String getStr() { + return str; + } + + /** + * @param str the str to set + */ + public void setStr(String str) { + this.str = str; + } + + /** + * @return the bean + */ + public AnotherBean getBean() { + return bean; + } + + /** + * @param bean the bean to set + */ + public void setBean(AnotherBean bean) { + this.bean = bean; + } + + } + + private static class AnotherBean { + private String name; + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.java new file mode 100755 index 0000000000..3627b2d094 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.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.tuscany.sca.databinding.xml; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class Node2StringTestCase extends TestCase { + public void testTransformation() throws Exception { + Document document = DOMHelper.newDocument(); + Element element = document.createElementNS("http://ns1", "test"); + document.appendChild(element); + + new Node2String().transform(document, null); + } +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.java new file mode 100644 index 0000000000..21d584e16c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.impl.PipedTransformer; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +public class PushTransformationTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransformation() { + String2XMLStreamReader t1 = new String2XMLStreamReader(); + XMLStreamReader reader = t1.transform(IPO_XML, null); + XMLStreamReader2SAX t2 = new XMLStreamReader2SAX(); + PipedTransformer<XMLStreamReader, ContentHandler, Node> t3 = + new PipedTransformer<XMLStreamReader, ContentHandler, Node>(t2, new SAX2DOMPipe()); + Node node = t3.transform(reader, null); + Assert.assertNotNull(node); + Node2String t4 = new Node2String(); + String xml = t4.transform(node, null); + Assert.assertTrue(xml != null && xml.indexOf("<shipDate>1999-12-05</shipDate>") != -1); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/StAXHelperTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/StAXHelperTestCase.java new file mode 100644 index 0000000000..6344df674a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/StAXHelperTestCase.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.tuscany.sca.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +/** + * Test Case for StAXHelper + */ +public class StAXHelperTestCase extends TestCase { + private static final String XML = + "<a:foo xmlns:a='http://a' name='foo'><bar name='bar'>" + "<doo a:name='doo' xmlns:a='http://doo'/>" + + "</bar></a:foo>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testHelper() throws Exception { + XMLStreamReader reader = StAXHelper.createXMLStreamReader(XML); + String xml = StAXHelper.save(reader); + reader = StAXHelper.createXMLStreamReader(xml); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.java b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.java new file mode 100644 index 0000000000..b5758d2149 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.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.tuscany.sca.databinding.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.net.URL; + +import junit.framework.TestCase; + +import org.w3c.dom.Node; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * + */ +public class TraxTransformerTestCase extends TestCase { + private URL url; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + url = getClass().getResource("foo.xml"); + } + + public void testTransformDOM() throws IOException { + InputStream is = url.openStream(); + InputStream2Node t1 = new InputStream2Node(); + Node node = t1.transform(is, null); + is.close(); + Writer writer = new StringWriter(); + Node2Writer t2 = new Node2Writer(); + t2.transform(node, writer, null); + String str = writer.toString(); + StringReader reader = new StringReader(str); + Reader2Node t3 = new Reader2Node(); + node = t3.transform(reader, null); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Node2OutputStream t4 = new Node2OutputStream(); + t4.transform(node, os, null); + InputSource inputSource = new InputSource(new ByteArrayInputStream(os.toByteArray())); + InputSource2Node t5 = new InputSource2Node(); + node = t5.transform(inputSource, null); + } + + public void testTransformSAX() throws IOException { + MyContentHandler handler = new MyContentHandler(); + InputStream is = url.openStream(); + InputStream2SAX t1 = new InputStream2SAX(); + t1.transform(is, handler, null); + is.close(); + + String xml = "<foo xmlns=\"http://foo\">bar</foo>"; + + InputSource inputSource = new InputSource(new StringReader(xml)); + InputSource2SAX t2 = new InputSource2SAX(); + MyContentHandler handler2 = new MyContentHandler(); + t2.transform(inputSource, handler2, null); + + } + + private static class MyContentHandler extends DefaultHandler { + + @Override + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) + throws SAXException { + super.startElement(namespaceURI, localName, qName, atts); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd new file mode 100644 index 0000000000..92a576fb98 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd @@ -0,0 +1,136 @@ +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<schema targetNamespace="http://www.example.com/IPO" + xmlns="http://www.w3.org/2001/XMLSchema" + xmlns:ipo="http://www.example.com/IPO"> + + <annotation> + <documentation xml:lang="en"> + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + </documentation> + </annotation> + + + <element name="purchaseOrder" type="ipo:PurchaseOrderType" /> + + <element name="comment" type="string" /> + + <complexType name="PurchaseOrderType"> + <sequence> + <element name="shipTo" type="ipo:Address" /> + <element name="billTo" type="ipo:Address" /> + <element ref="ipo:comment" minOccurs="0" /> + <element name="items" type="ipo:Items" /> + </sequence> + <attribute name="orderDate" type="date" /> + </complexType> + + <complexType name="Items"> + <sequence> + <element name="item" minOccurs="0" maxOccurs="unbounded"> + <complexType> + <sequence> + <element name="productName" type="string" /> + <element name="quantity"> + <simpleType> + <restriction base="positiveInteger"> + <maxExclusive value="100" /> + </restriction> + </simpleType> + </element> + <element name="USPrice" type="decimal" /> + <element ref="ipo:comment" minOccurs="0" /> + <element name="shipDate" type="date" + minOccurs="0" /> + </sequence> + <attribute name="partNum" type="ipo:SKU" + use="required" /> + </complexType> + </element> + </sequence> + </complexType> + + <simpleType name="SKU"> + <restriction base="string"> + <pattern value="\d{3}-[A-Z]{2}" /> + </restriction> + </simpleType> + + <complexType name="Address"> + <sequence> + <element name="name" type="string" /> + <element name="street" type="string" /> + <element name="city" type="string" /> + </sequence> + </complexType> + + <complexType name="USAddress"> + <complexContent> + <extension base="ipo:Address"> + <sequence> + <element name="state" type="ipo:USState" /> + <element name="zip" type="positiveInteger" /> + </sequence> + </extension> + </complexContent> + </complexType> + + <complexType name="UKAddress"> + <complexContent> + <extension base="ipo:Address"> + <sequence> + <element name="postcode" type="ipo:UKPostcode" /> + </sequence> + <attribute name="exportCode" type="positiveInteger" + fixed="1" /> + </extension> + </complexContent> + </complexType> + + <!-- other Address derivations for more countries --> + + <simpleType name="USState"> + <restriction base="string"> + <enumeration value="AK" /> + <enumeration value="AL" /> + <enumeration value="AR" /> + <enumeration value="CA" /> + <enumeration value="PA" /> + <!-- and so on ... --> + </restriction> + </simpleType> + + <simpleType name="Postcode"> + <restriction base="string"> + <length value="7" fixed="true" /> + </restriction> + </simpleType> + + + <simpleType name="UKPostcode"> + <restriction base="ipo:Postcode"> + <pattern value="[A-Z]{2}\d\s\d[A-Z]{2}" /> + </restriction> + </simpleType> + + + +</schema> + diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl new file mode 100644 index 0000000000..100890e10b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl @@ -0,0 +1,76 @@ +<?xml version="1.0"?>
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+<definitions name="StockQuote" targetNamespace="http://example.com/order.wsdl" xmlns:tns="http://example.com/order.wsdl"
+ xmlns:xsd1="http://example.com/order.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://schemas.xmlsoap.org/wsdl/">
+
+ <types>
+ <schema targetNamespace="http://example.com/order.xsd" xmlns="http://www.w3.org/2001/XMLSchema"
+ xmlns:ipo="http://www.example.com/IPO">
+ <import namespace="http://www.example.com/IPO" schemaLocation="ipo.xsd"/>
+ <element name="checkOrderStatus">
+ <complexType>
+ <sequence>
+ <element name="customerId" type="string" />
+ <element name="order" type="ipo:PurchaseOrderType" />
+ <element name="flag" type="int" />
+ </sequence>
+ </complexType>
+ </element>
+ <element name="checkOrderStatusResponse">
+ <complexType>
+ <sequence>
+ <element name="status" type="string" />
+ </sequence>
+ </complexType>
+ </element>
+ <element name="note" type="string" />
+ </schema>
+ </types>
+
+ <message name="CheckOrderStatusInput1">
+ <part name="body" element="xsd1:checkOrderStatus" />
+ </message>
+
+ <message name="CheckOrderStatusOutput1">
+ <part name="body" element="xsd1:checkOrderStatusResponse" />
+ </message>
+
+ <message name="CheckOrderStatusInput2">
+ <part name="p1" element="xsd1:checkOrderStatus" />
+ <part name="p2" element="xsd1:note" />
+ </message>
+
+ <message name="CheckOrderStatusOutput2">
+ <part name="p1" element="xsd1:checkOrderStatusResponse" />
+ </message>
+
+ <portType name="OrderPortType">
+ <operation name="checkOrderStatus">
+ <input message="tns:CheckOrderStatusInput1" />
+ <output message="tns:CheckOrderStatusOutput1" />
+ </operation>
+ <operation name="checkOrderStatus2">
+ <input message="tns:CheckOrderStatusInput2" />
+ <output message="tns:CheckOrderStatusOutput2" />
+ </operation>
+ </portType>
+
+</definitions>
\ No newline at end of file diff --git a/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml new file mode 100644 index 0000000000..0ba8ade1e0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<f:foo xmlns:f="http://foo" name="foo"> + <b:bar xmlns:b="http://bar">bar</b:bar> +</f:foo>
\ No newline at end of file |